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
M(k,:) = []
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,:) = []
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
>> 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)
X =
0
1
0
1
0
0
>> N(X,:) = []
N =
1 2 3
0 5 0
6 7 0
8 9 10
Best Answer