maverick
maverick

Reputation: 68

Error while deleting cell array elements in matlab

I have following 1-D cell array:

obj = {'HotAirBalloon' 'Cloud' 'Sun' 'Lightning'};

I trying to delete its elements using a for loop in the following manner:

for i = 1:4

obj (i) = [ ];

end

But, I am getting error:

Index of element to remove exceeds matrix dimensions, and following elements remain in the 'obj' array: 'Cloud' 'Lightning'

If I repeat the operation (for loop), then the elements get deleted.

What's the problem ?

Upvotes: 1

Views: 75

Answers (1)

Rash
Rash

Reputation: 4336

There is no need for a loop

obj(1:4) = [];

Explanation of your code :

When you use loop in the first iteration (i = 1) you have obj(1) = [];, then obj has 3 elements,

obj = { 'Cloud' 'Sun' 'Lightning'}

In the second iteration obj(2)=[] which is actually obj(3) (sun). So at the end of second loop:

obj = { 'Cloud' 'Lightning'}

In the third iteration you have obj(3) = [] which exceeds dimension of obj and you get the error.

If you want to use loop you can use it like this,

for i = ones(1,4)
    obj(i) = [];
end 

Upvotes: 2

Related Questions