What does the following code display?
V=[2 4 6 8];
for V = 1:2:5
if V>=3
disp('yes')
else
disp('no')
end
end
disp(V);
I know the output is:
no
yes
yes
5
But I'm not sure why. What determines the yes and no answers, and why does the value of V become 5? Any help?

댓글 수: 1

phillip kataswa
phillip kataswa 2020년 3월 31일
The last number to iterate thorough the loop is 5. I think that instead of displaying the whole vector V
V is automatically changed to a scaler vector and only stores the last number that iterates through the loop.

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

답변 (2개)

Walter Roberson
Walter Roberson 2013년 3월 7일

0 개 추천

Try this:
X = 999;
for X = 777; end
disp(X)

댓글 수: 2

Brian C
Brian C 2013년 3월 7일
So, is it completely rewriting the value of X?
Walter Roberson
Walter Roberson 2013년 3월 7일
Yes.

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

Image Analyst
Image Analyst 2013년 3월 7일
편집: Image Analyst 2013년 3월 7일

0 개 추천

The first V you made is essentially thrown away and never used.
V=[2 4 6 8]; % Never used at all.
When you do this:
for V = 1:2:5
you're saying that, in the loop, you want V to take on values 1, 3, and 5. It means (startvalue):(stepValue):(endingValue). After the loop, V retains its last value of 5 and that's what you print out.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2013년 3월 7일

댓글:

2020년 3월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by