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

I have a variable a = 1. I want to generate a variable name of the form:

variableNumber  

So in this example, I would want

a1
a2
a3

as variables. How can I do that?


Solution 1:

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.

Solution 2:

Try genvarname.

varname = genvarname(str)

is the basic syntax for use. MATLAB documentation has detailed examples of using this function with an exclusion list (for ensuring unique variable names). You will have to use eval or another function (e.g. assignin, mentioned in an earlier answer) to utilise this variable name.

To answer the question completely,

varnamelist = genvarname({'a','a','a','a','a'});
for l=1:length(varnamelist)
  eval([varnamelist{l} '= l^2']);
end

Of course, there are more efficient ways of putting together an input list for genvarname, this is left as an exercise ;)

If you're concerned about performance, note that eval may slow down the script/function greatly; personally I would recommend the use of struct or cell datatypes if you need dynamic variable naming.

Solution 3:

Use assignin.

assignin('base', sprintf('variable%d', 1), 1:10)

EDIT: As JS mentioned, structs are generally better for dynamic field names. You can use them like this:

varnames = {'foo', 'bar'};
str = struct;
for i = 1:length(varnames)
   str = setfield(str, varnames{i}, rand); %#ok<SFLD>
end

str =    
     foo: 0.4854
     bar: 0.8003

Or even more simply, like this:

str2.('alpha') = 123;
str2.('beta') = 1:10;

Solution 4:

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

But if your answer is YES then that is your answer:

for k=1:5
  eval(['a' num2str(k) '= k;'])
end