Find the First element that satisfies a condition

96 ビュー (過去 30 日間)
Tyler
Tyler 2016 年 3 月 12 日
コメント済み: Jay Edelman 2023 年 8 月 11 日
I have an nxn matrix and would like to find the first element in each row that satisfies a given condition, and gives me NaN if there are none that meet the condition. The find command will give me all elements that satisfy it, but I only care about the first one in each row.
For instance, if my matrix is A = [7 3 9;5 8 8;0,2,6] and my condition is A<5, I would like to use a function that gives me [3 NaN 0] or at least tells me where in the matrix I can find those values and use it to index A.
Thanks!

採用された回答

Stephen23
Stephen23 2016 年 3 月 12 日
編集済み: Stephen23 2016 年 3 月 12 日
No loops or find is required, just some logical indexing does the trick:
>> A = [7 3 9;5 8 8;0,2,6];
>> B = A.'; % important: arrange the data columnwise
>> X = B<5;
>> Y = cumsum(X,1)==1 & X;
>> Z = any(Y,1);
>> out(Z) = B(Y);
>> out(~Z) = NaN
out =
3 NaN 0
  2 件のコメント
Tyler
Tyler 2016 年 3 月 12 日
Thanks! Is there a way to output only the index of each row?
Jay Edelman
Jay Edelman 2023 年 8 月 11 日
A = [7 3 9;5 8 8;0,2,6];
X = A < 5;
[r,c] = find(cumsum(X>0,2)==1 & X);
idxs = NaN(height(X),1);
idxs(r) = c;

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

その他の回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2016 年 3 月 12 日
編集済み: Andrei Bobrov 2016 年 3 月 14 日
t = A < 5;
x = cumsum(t,2) == 1 & t;
out = sum(x.*A,2);
out(~any(t,2)) = nan
idx = x*(1:size(A,2))'
  4 件のコメント
Star Strider
Star Strider 2016 年 3 月 14 日
My pleasure.
That is brilliant code!
Olubunmi Anthony Jeyifous
Olubunmi Anthony Jeyifous 2018 年 11 月 11 日
Hi I have a similar problem. I have a long column vector and i would like to know the first row number the condition is met.

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


Bill Tubbs
Bill Tubbs 2021 年 4 月 12 日
If you only want to find the locations in A where the condition is true and then index those values you can use find:
>> elements_idx = find(A<5)
elements_idx =
3
4
6
>> A(elements_idx)
ans =
0
3
2
Note: the indices in elements_idx are not (row, col) indices as you might expect for a matrix but linear indices starting in the top-left element and incrementing down through each column from left to right.

MHN
MHN 2016 年 3 月 12 日
編集済み: MHN 2016 年 3 月 12 日
If you dont mind a little coding:
A = [7 3 9;5 8 8;0,2,6];
FirstCon = zeros(size(A,1),1);
i=1;
B = A'; % I am going to use the power of Matlab for processing a whole column, so I have to reverse the original matrix, so the rows become columns.
for I = B
temp = I(I<5);
if isempty(temp)
FirstCon(i,1) = NaN;
else
FirstCon(i,1) = temp(1);
end
i=i+1;
end

カテゴリ

Help Center および File ExchangeParticle & Nuclear Physics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by