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 日
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 件のコメント
Walter Roberson
Walter Roberson 2020 年 4 月 29 日
編集済み: Walter Roberson 2020 年 4 月 29 日
dim1 = sum(cumprod(A==0,2),2)+1;
At the moment, a formula for dim2 is not coming to mind without using an assignment.
Watch out for the case where there is no non-zero: the dim1 output would be 1 more than the number of columns.
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 件のコメント
Walter Roberson
Walter Roberson 2020 年 4 月 30 日
[sorted,sorti] = sort(A~=0, 2,'descend');
rather than A>0, since A values might be negative
george pepper
george pepper 2020 年 4 月 30 日
great, thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by