How to solve "Index exceeds matrix dimensions" error?

My question might be simple for most of you. Basically, I would like to delete a row of a matrix where a value of an element in column 6 is zero. In doing so, I run the following command.
load filename.txt;
for i = 1:length(filename)
if filename(i,6) = 0;
filename(i,:) = [];
end
end
However, the error message comes up saying that "Index exceeds matrix dimensions.". I don't understand why it exceeds the dimension because I have already specified that i = 1 to the length of the matrix. Any help on this would be appreciated. Thank you.

 채택된 답변

Walter Roberson
Walter Roberson 2012년 2월 20일

2 개 추천

After you do the first deletion, the array is no longer as long as it used to be. The "for" limits are determined when the "for" is first encountered and are not adjusted at run-time.
(complete) Adjusted code:
load filename.txt
filename(filename(:,6) == 0, :) = [];

추가 답변 (2개)

Oleg Komarov
Oleg Komarov 2012년 2월 20일

1 개 추천

Because you're shrinking filename if the condition is verified.
Once you delete a row, the length of filename is one unit smaller but the loop is still setup from 1 to initial dimension of filename.
nfllover
nfllover 2012년 2월 20일

0 개 추천

Thank you very much for your help. I have now solved the problem.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by