How to rename a variable in a loop in MATLAB?

Can someone tell if there is a way to rename a variable in each loop iteration in MATLAB?

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

+4
source share
3 answers

Based on your comment, I suggest using a cell array . This allows you to store any type of result by index. For instance:

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

Then you can save foo to save all intermediate results. Although the loop index is not baked into the variable name as you want, it offers identical functionality.

+12
source

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 

Output:

 val1 = 10 val2 = 20 val3 = 30 
+8
source

Another way: using the structure to store the loop index in the name 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 .

0
source

Source: https://habr.com/ru/post/1496102/


All Articles