How to concatenate a number to a variable name in MATLAB?

My answer to this question is “Are you sure you really want to do that?”

If you have a series of variables like this, you are then going to have to figure out a way to refer to all those variables later, that will likely mean an EVAL or something else like that.

If you know that everything you will store in this will be a scalar, you could store them all in a vector:

a(1) = 1;
a(2) = 2;
a(3) = 3;

What if you do not have scalars?

a{1} = 1;
a{2} = 'Doug';
a{3} = [1 2 3 4];

Then you can refer to these as a{1} or whatever.

Unless you have a good reason to do this, you are better off making a cell array, array of structures, vector, or something else.

Leave a Comment