Trouble understanding 'for' loops

조회 수: 4 (최근 30일)
Justin Yeung
Justin Yeung 2020년 2월 8일
댓글: Justin Yeung 2020년 2월 8일
So if given this vector:
N = [10,100,500,1000,2000,3000,4000,5000];
for k=1:length(N)
end
Why is my value for 'k' only returning 8? Shouldn't it be returing a row vector [1 2 3 4 5 6 7 8]

채택된 답변

Walter Roberson
Walter Roberson 2020년 2월 8일
N = [10,100,500,1000,2000,3000,4000,5000];
for k=1:length(N)
k
end
When you have a for loop, then the loop variable is assigned the first column in the list of values, and then the body of the loop is executed. Then the loop variable is assigned the second column in the list of values, and the body of the loop is executed. Then the loop variable is assigned the third column in the list of values... and so on. Eventually the loop variable will be assigned the last value, and the body of the loop will be executed.
Notice that at the end of all of that, the loop variable will still have the value of the last column -- which would be 5000 in this case. The loop variable is assigned one value at a time (unless you are doing strange things with columns), and at the end the loop variable is left as that one value.
The loop variable is not set to all of the value simultaneously, only to one value at a time.
  댓글 수: 1
Justin Yeung
Justin Yeung 2020년 2월 8일
OK. I get it now! Thank you!

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

추가 답변 (0개)

카테고리

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