Finding a row with a certain value and the next nth rows after that

Hi
I would like to find a row with a specific value and the next nth rows after that.
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 5
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
0.9134 0.9575 0.4854 0.7922 5
0.6324 0.9649 0.8003 0.9595 0.6787
0.6324 0.9649 0.8003 0.9595 0.6787
So in the above example, i would like to find the last column == 5 and then the next two rows and extract those.
I know how to index and find column ==5 , but not how to find the next two rows.
thanks

4 Comments

Let's work thru -- how did you find the values you did? Show us your code.
And, what's the wanted output; the problem definition is not totally clear -- do you want both sets that could be returned from teh above array, only the first, only the last...???
Hello,
I think i have a solution for my own problem ;
First i found the index i was interested in:
idx=find(data(:,lastcol)==5)
I use the index to access the rows i want until the nth row i need, meaning the first value in the last column that satifies == 5 and the subsequently 2 rows after that
n=2
data(idx:idx+n,row)
hope it makes sense
Pretty-much...altho you didn't answer the Q? posed of what, precisely is the wanted output?
Your code snippet above doesn't define lastcol nor row so can't tell for sure...if you set
lastcol=size(data,2);
note this would be a place to use the builtin addressing expression end that will return the size in the direction of an array in the direction corresponding to the position in the addressing expression it appears.
Similarly, if
row=[1:lastcol];
or equivalent, then you can write
idx=find(data(:,end)==5);
v=data(idx:idx+2,:);
NB: However, this returns only rows 3:5, not 3:5 and 6:8 which also satisfy the request.
Okay, Thanks for the help! and sorry for not being clear.
Matt J's answers was what i was looking for excatly :D

Sign in to comment.

 Accepted Answer

Here's an approach that uses logical indexing only:
A=[ 0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 5
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
0 1 2 3 0.4
0 1 2 3 0.4
0.9134 0.9575 0.4854 0.7922 5
0.6324 0.9649 0.8003 0.9595 0.6787
0.6324 0.9649 0.8003 0.9595 0.6787
0 1 2 3 0.4];
idx = movmax(A(:,end)==5,[2,0]);
A(idx,:)
ans = 6×5
0.1270 0.5469 0.9572 0.9157 5.0000 0.9134 0.9575 0.4854 0.7922 0.9340 0.6324 0.9649 0.8003 0.9595 0.6787 0.9134 0.9575 0.4854 0.7922 5.0000 0.6324 0.9649 0.8003 0.9595 0.6787 0.6324 0.9649 0.8003 0.9595 0.6787

More Answers (0)

Categories

Tags

Asked:

on 18 Feb 2021

Commented:

on 21 Feb 2021

Community Treasure Hunt

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

Start Hunting!