Loop backwards and select subset of rows that meet criteria

1 visualización (últimos 30 días)
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

Respuesta aceptada

Gareth Lee
Gareth Lee el 18 de Oct. de 2016
Editada: Gareth Lee el 18 de Oct. de 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)))
  1 comentario
Tyler Smith
Tyler Smith el 18 de Oct. de 2016
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.

Iniciar sesión para comentar.

Más respuestas (1)

Gareth Lee
Gareth Lee el 18 de Oct. de 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,:);

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by