Finding the first element of a matrix that satisfy a condition in a frequently manner
38 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I have a large matrix of data (10000x6). As you can see in the following I am imposing a condition on my data, and this condition is true in a frequent manner. The thing is I want to extract just the first element whenever the condition is true (the marked points in the image) and exclude the other elements which satisfy the condition. I would be very thankful if someone could tell me how can I do this.
Thank you,
Shahin
y_coordinate=D(6:N_atom:end,:); TR=zeros(size(y_coordinate)); aa=1; for jj=1:length(y_coordinate) if y_coordinate(jj,2)<31.35 && y_coordinate(jj,4)<0 TR(aa,:)=y_coordinate(jj,:); aa=aa+1; end end
回答 (3 件)
Adam Danz
2018 年 9 月 21 日
編集済み: Adam Danz
2018 年 9 月 23 日
... I want to extract just the first element whenever the condition is true...
This line below will return the index value of the first row that is true.
% Find the first index where condition is true (empty if none are true)
firstTrueIdx = find(y_coordinate(:,2)<31.35 & y_coordinate(:,4)<0, 1);
Now you can use firstTrueIdx| to identify the row number of that element. If it's empty, that means there were no true values.
0 件のコメント
Bruno Luong
2018 年 9 月 22 日
編集済み: Bruno Luong
2018 年 9 月 22 日
Your loop is equivalent to
condmeet = y_coordinate(:,2)<31.35 & y_coordinate(:,4)<0;
TR = y_coordinate(condmeet ,:);
If you want to find the first element then
ifirst = find(condmeet,1,'first');
FirstTR = y_coordinate(ifirst ,:);
it returns empty array if no row meets the condition.
3 件のコメント
Bruno Luong
2018 年 9 月 23 日
Not sure about your comment Adam: the other answers need loop (with index jj), mine does not. Or you make a type with jj?
shahin mohammadnejad
2018 年 9 月 23 日
6 件のコメント
Adam Danz
2018 年 9 月 24 日
編集済み: Adam Danz
2018 年 9 月 24 日
Oh, that could be achieved by changing the last line of my code above.
condmeetIdx = find(condmeet);
deltaIdx = [diff(condmeetIdx),0];
condmeetIdx(deltaIdx==1) = [];
TR = zeros(size(y_coordinate));
TR(condmeetIdx,:) = y_coordinate(condmeetIdx, :);
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!