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

1,920 ビュー (過去 30 日間)
Jan 2012 年 12 月 26 日

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

#### 6 件のコメント

Stephen Cobeldick 2017 年 4 月 21 日
Here is another explanation of why dynamic variable names are bad way to write code, with links to many other answers and forums:
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 all of the linked pages.
Jan 2017 年 4 月 24 日
@Huw S: When a user asks for a method to drill a hole in his knee to increase the running speed, detailed instructions would not be useful also. The best answer is: "This is the wrong approach, because it produces more problems than it solves."
There is always a better way to solve a problem.
Jan 2019 年 3 月 15 日
[MOVED from flags] Alexandre THIBEAULT wrote at Stephen's comment:
"cmon, we will not read all of the content of all of the pages... We are looking for solutions."
@Alexandre: You find solutions, when you scroll down and read the answer. Stephen's exhaustive explanations have been required after hundreds of discussions in the last years.

サインインしてコメントする。

### 採用された回答

Jan 2012 年 12 月 26 日

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
end
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;
end
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}));
end
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));
end
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 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)]);

#### 1 件のコメント

Edward Byers 2016 年 7 月 19 日
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."

サインインしてコメントする。

### その他の回答 (2 件)

Robert Cumming 2014 年 9 月 10 日

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
tic
eval ( 'a = zeros(10,10);' )
toc
% an alternate method is to use a
% sub function which assigns vars in the caller function:
tic
variableCreator ( 'b', zeros(10,10) )
toc
% validate that a and b both exist and are the same:
isequal ( a, b )
end
% Use a sub function which assigns variable in the caller function:
function variableCreator ( newVar, variable )
assignin ( 'caller', newVar, variable );
end
To complete Jans example you could use this in the following way:
for ii=1:10
variableCreator ( sprintf ( 'A%i', ii ), ii )
end
That would create variables A1, A2.... A10.

#### 3 件のコメント

Jan 2017 年 2 月 13 日
@Robert: +1. Thanks for this addition. assignin inside a function is indeed faster than an assignmennt in eval.
Please note, that the speed problem does not concern only the creation of the variables, but Matlab's JIT acceleration cannot handle the dynamically created variables efficiently:
v = zeros(1, 1e6);
tic;
for k = 1:1e6
v(k) = k;
end
toc
variableCreator('w', zeros(1, 1e6));
tic;
for k = 1:1e6
w(k) = k;
end
toc
Elapsed time is 0.003282 seconds.
Elapsed time is 0.039445 seconds.
The effects are much larger for nested loops or if multiple variables are concerned.
Oussama HAYANE 2020 年 1 月 1 日
Thank you very much for this answer
for ii=1:10
variableCreator ( sprintf ( 'A%i', ii ), ii )
end
it gives axactly what I looked for
Now, my quaestion is :
What can I do if I want to use one of these variables on an other loop
i.e. : how can I call them using Index 'A%i'
I want to modify a value of one these vriables but i don't know wich one : in my code I have a condition that determine wich one of these 'A%i' will be modified; so how can I call this 'A%i' to give it a new value
example: A5 = 8;
and I want to change it to : A5 = 19;
Stephen Cobeldick 2020 年 1 月 1 日
@Oussama HAYANE: use indexing. Indexing is much simpler and more efficient than what you are trying to do:
A(5) = 8;
A(5) = 19;
Indexing is explained quite well in the introductory tutorials:
Is there a particular reason why you need to write such slow, complex, obfuscated code?

サインインしてコメントする。

shahil kushwaha 2017 年 6 月 13 日
thanks a lot

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by