how to decrease for loop variable counter when deleting rows in a matrix
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Gideon Maasz
el 31 de Jul. de 2018
Respondida: Stephen23
el 31 de Jul. de 2018
I have an array A in which I delete rows based n a certain condition within another corresponding matrix which consists of the mean values of A. Each time I delete a row, I want my 'i' counter to jump back 1 iteration in order to not skip rows.
Means_Array=mean(A,2);
for i = 1:size(A,1)
if Means_Array(i,1)==0
Means_Array(i,:)=[];
A(i,:)=[];
i=i-1
end
end
This does however not work for some reason and the 'i' resets back to the value it would have taken if the i=i-1 was not even there.
0 comentarios
Respuesta aceptada
Stephen23
el 31 de Jul. de 2018
Just specify the for loop values to count downwards:
for i = size(A,1):-1:1
...
end
0 comentarios
Más respuestas (1)
Steven Lord
el 31 de Jul. de 2018
That is correct. In the documentation for the for keyword: "Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop."
Instead of deleting rows one by one in the loop, create a logical vector indicating either rows to keep or rows to delete, and use that logical vector after the loop is complete.
M = magic(5)
keep = true(size(M, 1), 1);
toDelete = false(size(M, 1), 1);
for therow = 1:size(M, 1)
if M(therow, 1) < 11
keep(therow, 1) = false;
toDelete(therow, 1) = true;
end
end
M2 = M(keep, :)
M3 = M;
M3(toDelete, :) = []
You don't need to use both keep and toDelete. I just wanted to show both techniques and this was the most compact way to do so.
0 comentarios
Ver también
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!