## Tuesday, December 20, 2005

### Matlab: a sequence of variable names

a1=5; a2= 14; a3=19;
for i=1:3
bb= eval(sprintf('a%-1d',i));
end
% bb=a1, a2, a3 ...this one shows changing a sequence of variable names.

Q3.6: How can I create variables A1, A2,...,A10 in a loop? (Matlab FAQ)

Don't do this. You will find that MATLAB arrays (either numeric or cell) will let you do the same thing in a much faster, much more readable way. For example, if A1 through A10 contain scalars, use:

A = zeros(1,10);        % Not necessary, just much fasterfor i=1:10A(i) = % some equationend

Now refer to A(i) whenever you mean Ai. In case each Ai contains a vector or matrix, each with a different size, you want to use cell arrays, which are intended exactly for this:

for i=1:10A{i} = 1:i;end

Note that each A{i} contains a different size matrix. And be careful to use the curly braces for the subscript!

Now, if you still really want to create variables with dynamically generated names, you need to use eval. With eval, you use MATLAB commands to generate the string that will perform the operation you intend. For example, eval('A=10') has the same effect as A=10, and eval(['A' 'B' '=10']) has the same effect as AB=10, only the eval method executes much more slowly. So in a loop, you could use:

for i=1:10eval(sprintf('A%d = [1:i]', i));end

Notice how much more obfuscated this is. Repeat: don't do this unless you have a very good reason (such as someone gives you a MAT file with 2000 variables named A1428, for example).