Finding the first element of a matrix that satisfy a condition in a frequently manner
8 views (last 30 days)
Show older comments
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
Answers (3)
Adam Danz
on 21 Sep 2018
Edited: Adam Danz
on 23 Sep 2018
... 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 Comments
Bruno Luong
on 22 Sep 2018
Edited: Bruno Luong
on 22 Sep 2018
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 Comments
Bruno Luong
on 23 Sep 2018
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
on 23 Sep 2018
6 Comments
Adam Danz
on 24 Sep 2018
Edited: Adam Danz
on 24 Sep 2018
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, :);
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!