Sanchit
Sanchit

Reputation: 3289

How to rename a variable in a loop in MATLAB?

Can somebody please tell if there exists a way to rename a variable in each iteration of a loop in MATLAB?

Actually, I want to save a variable in a loop with a different name incorporating the index of the loop. Thanks.

Upvotes: 4

Views: 12379

Answers (3)

Mikhail
Mikhail

Reputation: 21749

Ignoring the question, "why do you need this?", you can use the eval() function:

Example:

for i = 1:3
  eval(['val' num2str(i) '=' num2str(i * 10)]);
end

The output is:

val1 =
    10

val2 =
    20

val3 =
    30

Upvotes: 8

Yossarian
Yossarian

Reputation: 5471

Another way, using a struct to save the loop index into the name of the field:

for ii=1:bar
    foo.(["var" num2str(ii)]) = quux;
end

This creates a structure with fields like foo.var1, foo.var1 etc. This does what you want without using eval.

Upvotes: 0

Marc Claesen
Marc Claesen

Reputation: 17026

Based on your comment, I suggest using a cell array. This allows any type of result to be stored by index. For example:

foo=cell(bar,1);
for ii=1:bar
    foo{ii}=quux;
end

You can then save foo to retain all your intermediate results. Though the loop index is not baked into the variable name as you want, this offers identical functionality.

Upvotes: 12

Related Questions