Index exceeds matrix dimentions
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
pamela sulis
le 27 Oct 2015
Commenté : pamela sulis
le 27 Oct 2015
My question might be simple for most of you. Basically, I would like to delete a row of a matrix where a value of the elements in columns from 2 to 7 is zero. In doing so, I run the following command.
for i=1:size(StayCell,1)
if StayCell(i,2:7)==0
StayCell(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.
I try also this codes but i have the same problems
for i=length(StayCell)
if(StayCell(:,2:7)==0)
StayCell(i,:)=[];
end
end
StayCell(StayCell(:,2:7)==0,:)=[];
3 commentaires
Eng. Fredius Magige
le 27 Oct 2015
Modifié(e) : Eng. Fredius Magige
le 27 Oct 2015
Hi try this if(~all(StayCell(:,2:7))) instead of if(StayCell(:,2:7)==0)
Réponse acceptée
Stephen23
le 27 Oct 2015
Modifié(e) : Stephen23
le 27 Oct 2015
The Problem
That error message tells us that you are trying to access a non-existent row of a matrix. Your code deletes rows of the matrix, and then tries to access rows of the original matrix size, but you do not take into account that that matrix has changed size since the start of the loop.
Lets have a look at an example script that does that same as your code:
M = [1,2;3,4;5,6]
for k = 1:size(M,1)
k % row to be removed
M(k,:) = [] % remove row
end
I did not put semi-colons on the lines, so we can see what happens as the loop iterates. This is what it displays in the command window:
M =
1 2
3 4
5 6
k =
1
M =
3 4
5 6
k =
2
M =
3 4
k =
3
Index of element to remove exceeds matrix dimensions.
Error in temp (line 6)
M(k,:) = [] % remove row
We can see the matrix is getting smaller on each iteration: first three rows, then two, then one. On the iteration with the error the matrix has just one row, but the code tries to access the third row, because k==3.
The loop does not know when you matrix has changed size, and so you are telling it to access every row of the original size of the matrix, not the size that it has after rows have been removed from it.
The Solution
Avoid ugly loops and learn to use MATLAB efficiently: different types of indexing and lots of code vectorization are your main tools to neat, fast, and efficient MATLAB code. You will likely need to use all or any too:
>> N = [1,2,3;4,0,0;0,5,0;0,0,0;6,7,0;8,9,10]
N =
1 2 3
4 0 0
0 5 0
0 0 0
6 7 0
8 9 10
>> X = all(N(:,2:3)==0,2) % rows where column 2 & 3 are both zero
X =
0
1
0
1
0
0
>> N(X,:) = [] % use X as logical index
N =
1 2 3
0 5 0
6 7 0
8 9 10
5 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!