Effacer les filtres
Effacer les filtres

how to save variable with different name inside loop?

42 vues (au cours des 30 derniers jours)
Pratik Oak
Pratik Oak le 8 Jan 2018
Commenté : Jan le 8 Jan 2018
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 commentaire
Stephen23
Stephen23 le 8 Jan 2018
Modifié(e) : Stephen23 le 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.

Connectez-vous pour commenter.

Réponse acceptée

Birdman
Birdman le 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 commentaires
Birdman
Birdman le 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
Jan le 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by