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.
댓글 수: 0
채택된 답변
Stephen23
2018년 7월 31일
Just specify the for loop values to count downwards:
for i = size(A,1):-1:1
...
end
댓글 수: 0
추가 답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!