Entry Level Exam Question

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 comentario

phillip kataswa
phillip kataswa el 31 de Mzo. de 2020
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.

Iniciar sesión para comentar.

Respuestas (2)

Walter Roberson
Walter Roberson el 7 de Mzo. de 2013

0 votos

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

2 comentarios

Brian C
Brian C el 7 de Mzo. de 2013
So, is it completely rewriting the value of X?
Walter Roberson
Walter Roberson el 7 de Mzo. de 2013
Yes.

Iniciar sesión para comentar.

Image Analyst
Image Analyst el 7 de Mzo. de 2013
Editada: Image Analyst el 7 de Mzo. de 2013

0 votos

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.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 7 de Mzo. de 2013

Comentada:

el 31 de Mzo. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by