Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a variable in a loop in MATLAB?

Tags:

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.

like image 715
Sanchit Avatar asked Dec 01 '22 03:12

Sanchit


2 Answers

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.

like image 88
Marc Claesen Avatar answered Dec 06 '22 20:12

Marc Claesen


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
like image 34
Mikhail Avatar answered Dec 06 '22 21:12

Mikhail