フィルターのクリア

How do I find the index of the first element equal to 0 for each row of a matrix in a fast way

7 ビュー (過去 30 日間)
Hi,
I have a NxL matrix, how can I obtain a vector containing the index of the first element equal to 0 of each row of the matrix in in a fast way? Each row always has an element equal to 0 so don't worry about possible errors of that kind. I would like to use the command 'find' in such a way that with one single call it gives me back the entire vector idx which, at the moment, I obtain in the following way:
(M is the given matrix)
idx=zeros(N,1)
for k=1:N
idx(k)=find(M(k,:)==0,1);
end

回答 (2 件)

Walter Roberson
Walter Roberson 2022 年 6 月 29 日
You cannot do it with a single find()
A vectorized way to do it is
M = ones(5,10); M(randperm(50,10)) = 0;
M
M = 5×10
1 1 1 1 0 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1
idx = sum(cumprod(logical(M),2),2)+1;
idx
idx = 5×1
5 3 2 11 1
  1 件のコメント
Walter Roberson
Walter Roberson 2022 年 6 月 29 日
Sometimes when people have these kinds of questions, their setup does not have negative values or complex values. In that case, you can get the results in a single call using min() with two outputs.

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


Torsten
Torsten 2022 年 6 月 29 日
[~,idx] = max(M==0,[],2)
or
idx = arrayfun(@(k)find(M(k,:)==0,1),1:size(M,1))

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by