How to make variable names using for loop

조회 수: 35 (최근 30일)
Deokjae Jeong
Deokjae Jeong 2022년 10월 4일
댓글: Walter Roberson 2022년 10월 4일
I need to make a code like below:
v1=0;
v2=0;
v3=0;
v4=0;
v5=0;
but how can i use for loop? i tried like below, which does not work.
for k=1:50
v{k}=0;
end

답변 (1개)

Angelo Yeo
Angelo Yeo 2022년 10월 4일
for k=1:50
v(k)=0;
end
  댓글 수: 10
Stephen23
Stephen23 2022년 10월 4일
"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 2022년 10월 4일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by