Loop backwards and select subset of rows that meet criteria

1 回表示 (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by