MATLAB Answers

column dimensions of nonzero elements of each row in a matrix

2 views (last 30 days)
Hello,
I have a 10000 by 6 matrix that looks like
A=[0 0 0 0 1 1; 0 1 0 0 1 0; 0 0 1 1 0 0]
I would like to get 10000 by 1 vectors called dim1 and dim2 such that dim1 (dim2) contains the column number of the first (second) nonzero element in each row. In the above example,
dim1=[5;2;3];
dim2=[6;5;4];
Is there an easy way to write this without using a loop?
Thanks in advance.
  2 Comments

Sign in to comment.

Accepted Answer

Shunichi Kusano
Shunichi Kusano on 30 Apr 2020
Edited: Shunichi Kusano on 30 Apr 2020
Hi george,
How about this way?
[sorted,sorti] = sort(A, 2,'descend');
sorti(:,1) will be dim1 and sorti(:,2) will be dim2. If "A" has values more than 1, it must be
[sorted,sorti] = sort(A>0, 2,'descend');
hope this helps.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!