Tuesday, May 05, 2009

Matlab: Matrix Indexing

OP here.


Q:
How do you replace the first nonzero element in each row with -1 ?


A = [
50 75 0;
50 0 100;
0 75 100;
75 100 0;
0 75 100;
0 75 100];

to
-1 75 0
-1 0 100
0 -1 100
-1 100 0
0 -1 100
0 -1 100

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


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


A3:
A((cumsum(~~A, 2) == 1) & (A ~= 0)) = -1
% notice ~~A is equal to A ~= 0



No comments: