Azzera filtri
Azzera filtri

How to make variable names using for loop

12 visualizzazioni (ultimi 30 giorni)
Deokjae Jeong
Deokjae Jeong il 4 Ott 2022
I need to make a code like below:
but how can i use for loop? i tried like below, which does not work.
for k=1:50

Risposte (1)

Angelo Yeo
Angelo Yeo il 4 Ott 2022
for k=1:50
  10 Commenti
Stephen23 il 4 Ott 2022
"I dont have time right now because I need to finish it by tonight."
The inefficiency of your approach is not just runtime, but also programming and debugging time.
Walter Roberson
Walter Roberson il 4 Ott 2022
You want to define and initialize 50 individual variables, and then you want to put the values of the variables together in a vector. You then overwrite the content of the individual variables with the results of the call.
In your perception, how does that differ from starting with just creating the vector (without putting the values into individual variables), passing the vector to the function, and then having code that splits the function up into the variables? Considering that you overwrite the variables after the call, what is going on in the code that requires that the initial values are written into individual variables before being put into the vector?
When you have code like
A=0; B=0;
C = [A, B];
then at the time the [A, B] is executed, the current values associated with A and B are extracted and put together into the list, and the resulting list is just of values. MATLAB does not keep any memory of where the values came from. If you were to examine C afterwards, you would be completely unable to determine that the first element was copied from A and the second from B. C=[A, B] is not creating a formula. If you were to alter A to 5 afterwards, C would not suddenly start evaluating to [5,0].
So inside the function that is receiving x0, there is no way to examine (for example) the 19th element of the vector and query "Which variable name did this element come from?"
An expression such as C=[A, B] is not creating a list of addresses of A and B. You cannot, for example, say "write 7 into the variable that was used for the second element of C" and then expect that B will now have the value 7. Only the values associated with the variables make it into C, with absolutely no "history" kept of where the values came from.
And that means that you might as well just use x0=zeros(1,50); without writing the values into individual variables first.

Accedi per commentare.


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

Community Treasure Hunt

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

Start Hunting!

Translated by