Loop backwards and select subset of rows that meet criteria

1 次查看(过去 30 天)
I am trying to loop backwards to select rows that meet a certain criteria. The criteria is "t" which is a date. From there I need to loop backwards through the first column (which is a single datenum) for as long as the difference between the datenums is =1. Once the difference is no longer 1, the loop can stop and all rows in which the datenum had a difference of 1 can be saved. Here is an example: If t = 712896 and
A=
712572 1950 12 15 -0.68
712573 1950 12 16 -1.84
712574 1950 12 17 -1.81
712575 1950 12 18 -1.51
712576 1950 12 19 -1.49
712893 1951 11 1 -1.38
712894 1951 11 2 -2.56
712895 1951 11 3 -2.68
712896 1951 11 4 -2.90
712897 1951 11 5 -2.27
712898 1951 11 6 -1.83
712899 1951 11 7 -1.57
712900 1951 11 8 -1.80
So the output would be:
712893 1951 11 1 -1.38
712894 1951 11 2 -2.56
712895 1951 11 3 -2.68
Here is the loop I have so far:
for k=length(A):-1:1;
if A(k,1) == t;
(part I'm having trouble with)
end
end

采纳的回答

Gareth Lee
Gareth Lee 2016-10-18
编辑:Gareth Lee 2016-10-18
if you want to use loop, it is showed below:
tindex = find(A(:,1)==t);
for j = tindex:-1:2
if(A(j,1)-A(j-1,1)==1)
B(j-1,:)= A(j-1,:);
else
break;
end
end
reshape(nonzeros(B),'',nnz(any(B)))
  1 个评论
Tyler Smith
Tyler Smith 2016-10-18
When I don't use a loop I get the error "Subscript indices must either be real positive integers or logicals." But the loop version works great! Thanks.

请先登录,再进行评论。

更多回答(1 个)

Gareth Lee
Gareth Lee 2016-10-18
you can solve it without loop, e.g
B = find(diff(A(1:find(A(:,1)==t),1))~=1);
result = A(B(end)+1:find(A(:,1)==t)-1,:);

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by