how to save variable with different name inside loop?
26 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-1-8
编辑:Stephen23
2018-1-8
"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.
采纳的回答
Birdman
2018-1-8
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 个评论
Birdman
2018-1-8
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
2018-1-8
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!