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

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by Doug Hull
on 18 Jan 2011

How do I make variables like this in a loop?

Answer by Doug Hull
on 18 Jan 2011

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 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 = 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)]);

[From the MATLAB FAQ of Ancient Times]

Show 1 older comment

Walter Roberson
on 30 Dec 2011

You have used mat2cell in the past, http://www.mathworks.com/matlabcentral/answers/23537-converting-a-cell-array-into-numeric-arrays

You could continue to use that, or you could use blockproc() or (if your system is older) blkproc()

You could probably also do it using permute() and reshape()

yasmine
on 31 Dec 2011

yes i divided the images already in cell arrays and numeric arrays but now i want to access the first layer of every block (:,:,1) in an iterative manner

i will post a new question with code

Answer by Nobita
on 22 Jun 2013

Edited by Nobita
on 22 Jun 2013

Hey all, The first sorry because my language english not good. With this detail, i used ..............................................................

for i=1:3

eval(['A' num2str(i) '= i+2'])

end

.....................................................................

it run very good . it show A1=, A2=, A3=. But now i want a math:

.................................................................

for i=1:3

eval(['A' num2str(i) '= i+2'])

Bi=Ai + 2

end

.....................................................

I want make B1, B2, B3 from A1, A2, A3. If i use:

......................................

for i=1:3

eval(['A' num2str(i) '= i+2'])

eval(['B' num2str(i) '= 'A' num2str(i)+2'])

end

............................................

it not run. Please help me . Thanks 4 read

Walter Roberson
on 22 Jun 2013

eval(['B' num2str(i) '= 'A' num2str(i) '+2'])

Please remember that this is not at all recommended!

Jan Simon
on 22 Jun 2013

@Nobita: Please do not attach a new question to an existing thread. Note that such a thread-highjacking does not allow you to accept an answer and it confuses the readers of the original topic.

And as Walter and Doug have mentioned already: Using EVAL is a really bad idea.

## 0 Comments