简体   繁体   中英

How to find first '1' in every row in MATLAB

I have a matrix,

A = [ 0 0 0 0 0 0 1 1 1 1 0 0; 0 0 0 0 0 1 1 1 1 0 0 0; 0 0 0 0 0 0 1 1 1 1 0 0]

My question is, how to find the first '1' in each row. I want the output will show like this:

B = [7; 6; 7]

Meaning that, for the first row, the number 1 found on column number 7, second row found in column number 6 and so on.

You can use the second output of max , which gives the position of the maximum:

v = 1; % desired value
[~, B] = max(A==v, [], 2); % position of maxima along the second dimension

As a bonus, if there can be rows that don't contain the desired value, you can output 0 for those rows as follows:

[m, B] = max(A==v, [], 2);
B = B.*m;

Find cumulative sum of each row of A and use find to get the row and column subscripts of ones and then order the column subscripts according to rows to get the desired matrix B .

[rind,cind] = find(cumsum(A,2)==1);
[~, rind] = unique(rind);
B = cind(rind);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM