How can I store the output from each for loop as a unique variable?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Aamna Sami
am 7 Dez. 2017
Beantwortet: Birdman
am 7 Dez. 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 Kommentar
Stephen23
am 7 Dez. 2017
Bearbeitet: Stephen23
am 7 Dez. 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:
Akzeptierte Antwort
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!