Cell evaluate indexing - Index exceeds matrix dimensions.

why this code is generating the error "Index exceeds matrix dimensions"?
% code
a{1} = 90;
i = 1;
a{num2str(i)};

 Accepted Answer

Edit after Jan's warning: String/char variables can be used for indexing but in this problem '1' internally refers to 49, and in this case 49th element of cell does not exist, therefore
a{'1'}
is invalid.

4 Comments

This is not correct: You can use char variables as index, but the conversion to their ASCII values seems to be unexpected in the OP's problem.
But converting means changing it. Then, strings can be used for indexing if you convert them to double.
@cvklpstunc:
C = cell(1, 100);
C{97} = '97th cell string';
C{'a'}
This works. You do not have to convert the index, because char's are uint16 internally and the interpretation as index works implicitly.
Nevertheless, the actual problem of the OP was using a char as index, not the value of the char. Therefore you hit the point to solve the problem (+1), although the explanation is not correct.
I understood the point, so explaining once is enough :)

Sign in to comment.

More Answers (1)

Jan
Jan on 28 Nov 2017
Edited: Jan on 28 Nov 2017
You can use char variables as index, but they are converted to their ASCII value at first:
disp(double('a'));
x = 1:100;
disp(x('a')); % 97
So in your example the problem is, that the char '1' is interpreted as the numerical value 49 and a{49} does not exist.

Products

Asked:

on 28 Nov 2017

Edited:

on 28 Nov 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!