2.32 Replace the first nonzero element in each row in a matrix by some value

Problem: Given a matrix, replace the first nonzero element in each row by some a specific value. This is an example. Given matrix \(A\) below, replace the first non-zero element in each row by \(-1\), then

\(A=\begin {pmatrix} 50 & 75 & 0\\ 50 & 0 & 100\\ 0 & 75 & 100\\ 75 & 100 & 0\\ 0 & 75 & 100\\ 0 & 75 & 100 \end {pmatrix} \) will become \(B=\begin {pmatrix} -1 & 75 & 0\\ -1 & 0 & 100\\ 0 & -1 & 100\\ -1 & 100 & 0\\ 0 & -1 & 100\\ 0 & -1 & 100 \end {pmatrix} \)

Mathematica

A={ {50, 75,  0},{50, 0,   100}, 
    {0,  75,  100},{75, 100, 0}, 
    {0,  75,  100},{0,  75,  100}}; 
ReplacePart[A,DeleteDuplicates[ 
    Position[A,_?(#!=0&)], 
      (#1[[1]]==#2[[1]]&)]->-1]
 

Solution due to Bob Hanlon (from Mathematica newsgroup)

r=Union[Position[A,_?(# !=0&)], 
  SameTest->(#1[[1]]==#2[[1]]&)]; 
ReplacePart[A,r->-1]
 

Solution by Fred Simons (from Mathematica newsgroup)

r=Split[Position[A,_?(# !=0&),{2}], 
      #1[[1]]==#2[[1]]&][[All,1]]; 
ReplacePart[A,r->-1]
 

Solution due to Adriano Pascoletti (from Mathematica newsgroup)

r=(First /@ Split[#1,First[#1]===First[#2]&]&) 
       [Position[A,x_/;x!=0]] 
ReplacePart[A,r->-1]
 

Solution due to Oliver Ruebenkoenig (from Mathematica newsgroup)

r=First /@ SplitBy[ Drop[ArrayRules[ 
     SparseArray[A]][[All,1]],-1],First] 
ReplacePart[A,r->-1]
 

Solution due to Szabolcs Horvát (from Mathematica newsgroup)

r=MapIndexed[{First[#2],1+LengthWhile[#1,#==0&]}&,A] 
ReplacePart[A,r->-1]
 

These all give

{{-1,75,0},{-1,0,100},{0,-1,100}, 
{-1,100,0},{0,-1,100},{0,-1,100}}
 

Matlab

A=[50 75 0; 
   50 0 100; 
   0 75 100; 
   75 100 0; 
   0 75 100; 
   0 75 100]; 
 
[I,J] = ind2sub(size(A),find(A~=0)); 
[b,c] = unique(I,'first'); 
A(sub2ind(size(A),b,J(c)))=-1
 

This solution due to Bruno Luong (from matlab newsgroup)

B = cumsum(A~=0,2)>0 
B = [false(size(B,1),1) B] 
A(logical(diff(B,1,2))) = -1
 

This solution due to Jos from matlab newsgroup

A((cumsum(~~A,2)==1) & (A ~= 0)) = -1
 

The above solutions all give

A = 
    -1    75     0 
    -1     0   100 
     0    -1   100 
    -1   100     0 
     0    -1   100 
     0    -1   100
 

Maple

restart; 
A:=Matrix([[50,75,0], 
           [50,0,100], 
           [0,75,100], 
           [75,100,0], 
           [0,75,100], 
           [0,75,100]]); 
for n from 1 to LinearAlgebra:-RowDimension(A)  do 
    idx:=ArrayTools:-SearchArray(A[n,..],1); 
    if numelems(idx)<>0 then 
       A[n,idx[1]]:=-1; 
    fi; 
 od: 
A
 

Matrix(6, 3, [[-1, 75, 0], 
              [-1, 0, 100], 
              [0, -1, 100], 
              [-1, 100, 0], 
              [0, -1, 100], 
              [0, -1, 100]])