user3509735
user3509735

Reputation: 1

How to set all ones in a matrix to zero except the first of every column?

I have a matrix show as below in matlab :

[ 1 0 1;0 1 1;1 1 0 ]

How to refine it into this matrix show as below ?

[ 1 0 1;0 1 0; 0 0 0 ]

That means I just only want to take the first 1 appears in each column.

Thanks!

Upvotes: 0

Views: 1131

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112759

Another approach: use max to get the row and column indices of the first one in each column. This is possible because the second output of max gives the position of the first maximum of each column.

[val, row] = max(A);
col = find(val); %// if max value is 0 => there aren't any 1's in that column
result = zeros(size(A));
result(sub2ind(size(A),row,col)) = 1;

Upvotes: 1

Robert Seifert
Robert Seifert

Reputation: 25232

One of probably many possibilities:

result = ( cumsum(A,1) == A ) & A

result =

     1     0     1
     0     1     0
     0     0     0

Explanation: cumsum(A,1) == A filters out all lower 1 and ... & A sets upper zeros back to zero, as they got ones the step before.

Upvotes: 4

Related Questions