Loop backwards and select subset of rows that meet criteria

조회 수: 2 (최근 30일)
Tyler Smith
Tyler Smith 2016년 10월 18일
댓글: Tyler Smith 2016년 10월 18일
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