how to save variable with different name inside loop?
28 views (last 30 days)
Show older comments
I have variable with name x with varying size of some 10000*2. 2 columns are fix, row value changing. I am getting that variable inside the for loop.
How should I autosave variable inside loop ? Autonaming for every loop condition will be useful.
Please reply. I want to use variable and call it in some other code.
1 Comment
Stephen23
on 8 Jan 2018
Edited: Stephen23
on 8 Jan 2018
"Autonaming for every loop condition will be useful"
Only if your definition of "useful" is that it forces you to write slow, complex, buggy code that obfuscates the code intent and makes debugging much harder:
Just put your data into one array. Then this entire problem goes away. Solving problem through better code design is much preferred.
Accepted Answer
Birdman
on 8 Jan 2018
Dynamically naming variables is not recommended. It is slow and buggy. Check the following link:
A better approach would be saving them in a structure by using a for loop. For instance:
for k = 1:10
A.(sprintf('RandomVariable_%d', k)) = rand;
end
The above code will automatically name the fields of struct. Your variables will be stored in a struct, which will be nice. Hope this helps.
3 Comments
Birdman
on 8 Jan 2018
I referred to the following link about dynamically naming structure fields.
Also, structures gives the flexibility to store several data types, therefore this situation makes them more attractive. Same thing applies for cell, of course but I believe it is just a matter of choice.
Jan
on 8 Jan 2018
A cell is a better solution, because in e.g. "A.RandomVariable_277" an index is hidden inside the field name. Extracting it requires a kind of sscanf or fprintf method with an expensive conversion between a number and a string. With using a cell, the index can be used directly.
Hiding a number in a name is an indirect method and therefore less clear. Structs are much clearer than cells, if the data are related to a name and not to a numerical index. Therefore I agree with Guillaume.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!