MATLAB: Error message”Matrix index is out of range for deletion.”

error messageMATLAB

Hello,
I get this error message when I run my program. I will be grateful if helping me to fix this issue
I have attached the code.

Best Answer

Consider: vector V = [1 2 -3 -4 5] . Task: delete negative elements.
for K = 1 : length(V)
if V(K) < 0;
V(K) = [];
end
end
Now
V(1) = 1 > 0 so leave V(1) alone. V = [[1] 2 -3 -4 5]
V(2) = 2 > 0 so leave V(2) alone. V = [1 [2] -3 -4 5]
V(3) = -3 < 0 so delete V(3). V = [1 2 [] -4 5]
V(4) = 5 > 0 so leave V(4) alone. V = [1 2 -4 [5]]
V(5) does not exist so fail with V = [1 2 -4 5]
Why did you fail? Because after you removed an element from V, V was no longer as long as it used to be, and for only evaluates its boundaries once, not every time through the loop, so length(V) the first time was copied into internal memory and length(V) is not re-calculated when V changes.
Why is -4 still there? Because when you deleted element 3, the elements after that "fell down" to occupy the empty slot, so the -4 moved into the place the -3 was, and the algorithm never re-examines a slot it already examined.
How can you get around this problem? There are several different ways:
  • you can construct a vector indicating which elements you will need to delete, and then afterwards do a single deletion. For example, K = find(V<0); V(K) = [];
  • you can use a while loop moving forward, because while does re-examine the values of the boundaries. When you delete an element, do not advance the index, so that next iteration you re-examine the same location you were just looking at (which is now filled with what used to be next in line)
  • you can arrange so that you delete from back to front. This often works well.
Related Question