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)...
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.
1 Answer
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).