Jun Seo-He
Jun Seo-He

Reputation: 131

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.

Upvotes: 1

Views: 991

Answers (1)

Ryan Marizza
Ryan Marizza

Reputation: 294

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

Upvotes: 3

Related Questions