Azzera filtri
Azzera filtri

how to decrease for loop variable counter when deleting rows in a matrix

7 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Stephen23
Stephen23 il 31 Lug 2018
Just specify the for loop values to count downwards:
for i = size(A,1):-1:1
...
end

Più risposte (1)

Steven Lord
Steven Lord il 31 Lug 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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by