'Matrix index out of range during loop
a is an nxn matrix.
I have this code:
[m,n] = size(a);
x = zeros(m,1);
for j=1:1:n
if(j==1)
a(1,:) = [];
else
end
disp(a);
a(:,j) = [];
disp(x);
disp(a);
end
And it gives error on the line a(:,j) = []; which says
Matrix index is out of range for deletion.
Why? I dont understand, help appreciated.
Solution 1:[1]
Instead of:
for j=1:1:n
Try using:
for j=n:-1:1
What's going on is you're deleting columns starting from j=1 and therefore shortening your matrix each time. As soon as j is greater than the remaining number of columns in a, it will throw that error.
Iterating backwards as I am suggesting will solve this problem (because your index is decreasing at the same time as your matrix size is decreasing).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
