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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With