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

7 次查看(过去 30 天)
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.

采纳的回答

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

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by