column dimensions of nonzero elements of each row in a matrix

조회 수: 1(최근 30일)
george pepper
george pepper 2020년 4월 29일
댓글: george pepper 2020년 4월 30일
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,
Is there an easy way to write this without using a loop?
Thanks in advance.
  댓글 수: 2
george pepper
george pepper 2020년 4월 29일
Thanks! How do you write it with an assignment?

댓글을 달려면 로그인하십시오.

채택된 답변

Shunichi Kusano
Shunichi Kusano 2020년 4월 30일
편집: Shunichi Kusano 2020년 4월 30일
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.
  댓글 수: 3

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by