MATLAB Answers

Jan Simon

FAQ: How can I create variables A1, A2,...,A10 in a loop?

Asked by Jan Simon
on 26 Dec 2012
Latest activity Commented on by Edward Byers on 19 Jul 2016 at 6:52

How can I create variables A1, A2,..., A10 in a loop?


Jan Simon
on 26 Dec 2012

This is an experimental question only! There is no need to answer it and please to not vote for it. This is neither my question nor my answer, but only an example for a nicer, more convenient, more usable FAQ, which is less stuffed with commercials.


Here is another explanation of why dynamic variable names are bad way to write code, with links to many other answers and forums:

So before using dynamic variable names, try reading and understanding why it is a really bad idea, and read all of the links and references on that page.


No products are associated with this question.

2 Answers

Answer by Jan Simon
on 26 Dec 2012
 Accepted answer

Please 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 faster
for i=1:10
  A(i) = % some equation

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:10
  A{i} = 1:i;

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

Another way to have your cake and eat it too is to use structures instead of cell arrays. The fields of the structure can be the variable names you want. And you can index into them with dynamic field references. For example:

names = {'fred' 'sam' 'al'};
for ind = 1:length(names)
  s.(names{ind}) = magic(length(names{ind}));

In this case, you end up with the variable s, a structure, containing fields specified by the strings stored in the cell array names.

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:10
  eval(sprintf('A%d = [1:i]', i));

Notice how much more obfuscated this is. In addition, this can cause difficult-to-troubleshoot problems in your code, particularly if you try to dynamically create a variable with the same name as a function:

function y = mysin(x)
  eval('sin = 5;');
  y = sin(x);

Calling this function with "y = mysin(1)" will not return y = 5 (the first element of the sin variable created by EVAL) -- it will return the sine of 1, because when the function was parsed there was no variable named sin and so the usage of sin on the last line was parsed as a call to the built-in SIN function. The fact that a variable named sin existed at runtime is irrelevant; the parsetime "decision" takes precedence.

Repeat: don't create variables at runtime using EVAL unless you have a very good reason, such as someone gives you a MAT file with 2000 variables named A1428, for example. Even in that case, you can avoid EVAL:

% Assume the MAT-file example1.mat contains 2000 variables, A1 through A2000
S = load('example1.mat');
% S is now a struct array with 2000 fields, S.A1 through S.A2000.
% To access A1428, use:
x1 = S.A1428;
% If the "index" of the variable you want to access is stored in a variable:
k = 1428;
x2 = S.(sprintf('A%d', k));
x3 = S.(['A', num2str(k)]);


This answer is copied and slightly modifed from How_can_I_create_variables_A1,_A2,....A10_in_a_loop

  1 Comment

Edward Byers on 19 Jul 2016 at 6:52

Hi Is there a good way to store multiple iterated LinearModel objects? i.e. with an index notation that makes it easy to loop and call specific instances, I have tried:

mdl{x} = fitlm(tbl,modelspec);

But that doesn't work, as: "Assignment using () is not allowed for a FitObject."

Answer by Robert Cumming
on 10 Sep 2014
Edited by Robert Cumming
on 10 Sep 2014

I 100% agree with Jan that creating new variables on the fly is something that should be avoided - but if you must then please consider this alternative method:

 function generateVariableOnFly
   % lets tic/toc to compare the use of eval and assignin
   eval ( 'a = zeros(10,10);' )
   % an alternate method is to use a 
   % sub function which assigns vars in the caller function:
   variableCreator ( 'b', zeros(10,10) )
   % validate that a and b both exist and are the same:
   isequal ( a, b )  
 % Use a sub function which assigns variable in the caller function:
 function variableCreator ( newVar, variable )
   assignin ( 'caller', newVar, variable );

To complete Jans example you could use this in the following way:

 for ii=1:10
   variableCreator ( sprintf ( 'A%i', ii ), ii )

That would create variables A1, A2.... A10.


Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!