Create variables with names from strings

Potaito picture Potaito · Apr 19, 2013 · Viewed 65.1k times · Source

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.

Answer

Dan picture Dan · Apr 19, 2013

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