Create variables with names from strings

Let's assume that I want to create 10 variables which would look like this:

x1 = 1;
x2 = 2;
x3 = 3;
x4 = 4;
.
.
xi = i;

This is a simplified version of what I'm intending to do. Basically I just want so save code lines by creating these variables in an automated way. Is there the possibility to construct a variable name in Matlab? The pattern in my example would be ["x", num2str(i)]. But I cant find a way to create a variable with that name.


Solution 1:

You can do it with eval but you really should not

eval(['x', num2str(i), ' = ', num2str(i)]); %//Not recommended

Rather use a cell array:

x{i} = i

Solution 2:

I also strongly advise using a cell array or a struct for such cases. I think it will even give you some performance boost.

If you really need to do so Dan told how to. But I would also like to point to the genvarname function. It will make sure your string is a valid variable name.

EDIT: genvarname is part of core matlab and not of the statistics toolbox

Solution 3:

for k=1:10
   assignin('base', ['x' num2str(k)], k)
end

Solution 4:

Although it is long overdue, i justed wanted to add another answer.

the function genvarname is exactly for these cases

and if you use it with a tmp structure array you do not need the eval cmd

the example 4 from this link is how to do it http://www.mathworks.co.uk/help/matlab/ref/genvarname.html

 for k = 1:5
   t = clock;
   pause(uint8(rand * 10));
   v = genvarname('time_elapsed', who);
   eval([v ' = etime(clock,t)'])
   end

all the best

eyal

Solution 5:

If anyone else is interested, the correct syntax from Dan's answer would be:

eval(['x', num2str(i), ' = ', num2str(i)]);

My question already contained the wrong syntax, so it's my fault.