how to save variable with different name inside loop?

28 次查看(过去 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
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
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
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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by