Finding column index of the first instance of 1

5 ビュー (過去 30 日間)
Pelajar UM
Pelajar UM 2022 年 5 月 2 日
コメント済み: Walter Roberson 2022 年 5 月 3 日
I have a logical array like this:
I want to extrat the colum index of the cells where the first instance of 1 is detected. Like this:
For example, you see here that the first two rows show 4, because that is where 1 is first detected.

採用された回答

Walter Roberson
Walter Roberson 2022 年 5 月 2 日
C = sum(cumprod(~X, 2),1) + 1;
C will be one more than the number of columns for any row that has no 1.
  4 件のコメント
Pelajar UM
Pelajar UM 2022 年 5 月 3 日
編集済み: Pelajar UM 2022 年 5 月 3 日
Thanks @Torsten. The second line gives a warning:
Unexpected use of '[' in a scalar context.
And it appears to break the loop already in k=1.
Instead we can use
if isempty(idx) == 1
break
end
But checking idx in every loop takes longer.
Method 1: 22 seconds
Method 2: 528 seconds
Walter Roberson
Walter Roberson 2022 年 5 月 3 日
isempty(idx)

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

その他の回答 (1 件)

Jonas
Jonas 2022 年 5 月 2 日
use the find() function together with a loop over each row
  1 件のコメント
Pelajar UM
Pelajar UM 2022 年 5 月 2 日
編集済み: Pelajar UM 2022 年 5 月 2 日
Like this?
Doesn't work, because it doesn't find the first instance. It finds all the indices that meet this condition.
for p=1:n %n is the length of the logical array X
G(p,:)=find (X(p,:));
end

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by