Loop backwards and select subset of rows that meet criteria
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Tyler Smith
il 18 Ott 2016
Commentato: Tyler Smith
il 18 Ott 2016
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
0 Commenti
Risposta accettata
Gareth Lee
il 18 Ott 2016
Modificato: Gareth Lee
il 18 Ott 2016
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)))
Più risposte (1)
Gareth Lee
il 18 Ott 2016
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,:);
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!