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

1 visualizzazione (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 7 Dic 2017
Modificato: Stephen23 il 7 Dic 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:

Accedi per commentare.

Risposta accettata

Birdman
Birdman il 7 Dic 2017
Store the data in one array as follows:
result(x)=M1+M2+M3;

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by