how to decrease for loop variable counter when deleting rows in a matrix
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gideon Maasz
le 31 Juil 2018
Réponse apportée : Stephen23
le 31 Juil 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 commentaires
Réponse acceptée
Stephen23
le 31 Juil 2018
Just specify the for loop values to count downwards:
for i = size(A,1):-1:1
...
end
0 commentaires
Plus de réponses (1)
Steven Lord
le 31 Juil 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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!