How can I store the output from each for loop as a unique variable?

1 vue (au cours des 30 derniers jours)
Aamna Sami
Aamna Sami le 7 Déc 2017
How can I store the output for each loop as a seperate variable. Eg. for k=3 creates 3 variable, total_year1, total_year2 and total_year 3...total_yeark?
k= input('Enter the no. of years'); for x=1:k M1=input(strcat('Enter the number of runs in year',' ', num2str(x),'match 1')) M2=input(strcat('Enter the number of runs in year',' ', num2str(x),'match 2')) M3=input(strcat('Enter the number of runs in year',' ',num2str(x), 'match 3')) total_year1=(M1+M2+M3) end
  1 commentaire
Stephen23
Stephen23 le 7 Déc 2017
Modifié(e) : Stephen23 le 7 Déc 2017
"How can I store the output for each loop as a seperate variable. Eg. for k=3 creates 3 variable, total_year1, total_year2 and total_year 3...total_yeark?"
That is exactly what you should not do. Magically creating or accessing variable names is how beginners write complex, slow, inefficient, buggy code. It is much better to use indexing: faster, neater, simpler, easier to debug, much more efficient.
The documentation has an entire page which explains why you should avoid doing exactly what you are asking about. It states: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array." Storing your data in one array and using indexing is what you should be doing.
You might like to read this to know more:

Connectez-vous pour commenter.

Réponse acceptée

Birdman
Birdman le 7 Déc 2017
Store the data in one array as follows:
result(x)=M1+M2+M3;

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by