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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest