olamundo
olamundo

Reputation: 24991

matlab: "Index of element to remove exceeds matrix dimensions." When I am not removing any elemens

I get the error

???  Index of element to remove exceeds matrix dimensions.

Error in ==> myfile at 111
    C(i)=s{i,3};

the code being:

C=zeros(num_of_tris,1);
for i=1:size(C,1)
    C(i)=s{i,3};
end

I'm not showing the code for creating s, but I assume it's beside the point as s only appears on the right hand side of the assignment...

why does it say element to remove? which element am I removing?

Upvotes: 2

Views: 4745

Answers (1)

abcd
abcd

Reputation: 42235

Ok, so here's what is happening. s is probably initialized to an empty cell (NOTE: need not be entirely empty -- see last paragraph). So, indexing an element of s as s{i,3} returns []. The MATLAB operation to remove an element of a vector is

C(i)=[];

So when you loop through, you're removing the elements of C one by one, and eventually, the index i exceeds the size of the (now diminished) vector.

Here's a small example that reproduces your problem:

s=cell(10,5);           %#initialize s to an empty cell
%#note that any cell returns []
s{3,4}

ans =

     []

%#This is your code from above
C=zeros(10,1);          %#initialize C
for i=1:size(C,1)
    C(i)=s{i,3};
end

??? Index of element to remove exceeds matrix dimensions.

You'll find that the index i when you get this error is numel(C)/2+1. In other words, till i=5 (in this example), you're removing every odd element of C and at i=6, the number of elements remaining in C is 5, and so you get an index out of bounds error.


NOTE:

s need not even be entirely empty. Consider this example:

s=cell(10,1);
s([1,2,6,8])=num2cell(rand(4,1));
C=zeros(10,1);
for i=1:numel(C)
    C(i)=s{i};
end

??? Index of element to remove exceeds matrix dimensions.

Upvotes: 4

Related Questions