Failure of the Continue command in a for-loop
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Robert Mason
el 31 de Jul. de 2016
Comentada: Image Analyst
el 31 de Jul. de 2016
I cannot get the continue command to work in for-loops. For instance, with the code:
q(1) = 1;
q(2) = 2;
q(3) = 3;
q(4) = 4;
q(5) = 5;
for j=1:5
if j==2
continue
end
qv=q
end
I expected the outcome of executing this code to be qv = [1 3 4 5], however the actual outcome is qv = [1 2 3 4 5].
Any suggestions as to how to get "continue" to work in this for-loop so that the output qv = [1 3 4 5] results?
0 comentarios
Respuesta aceptada
Star Strider
el 31 de Jul. de 2016
You’re not ‘building’ your ‘qv’ vector. You must also index ‘q’ since:
qv = q
sets ‘qv’ to all of ‘q’ in each iteration.
See if this does what you want:
q(1) = 1;
q(2) = 2;
q(3) = 3;
q(4) = 4;
q(5) = 5;
qv = []; % Initialise ‘qv’
for j=1:5
if j==2
continue
end
qv=[qv q(j)]; % Concatenate New Value
end
qv
qv =
1 3 4 5
One other observation:
q = 1:5;
q = [1 2 3 4 5];
will do the same assignment to ‘q’. The first creates a sequential vector, the second can contain any numbers you want (here consecutive, but they don’t have to be).
0 comentarios
Más respuestas (1)
Image Analyst
el 31 de Jul. de 2016
You constructed the for loop incorrectly. j takes on only the values 1 and 5. If you want it to take on the values 1,2,3,4 & 5, do this:
for j = 1 : 5
By the way, I fixed your code formatting. For your next post, read this link to learn how to format.
Also see this link to learn how you can step through code to see what values, such as your "j", take on at each line in your program.
2 comentarios
Image Analyst
el 31 de Jul. de 2016
I seriously doubt that.
for j = [1 5]
disp(j);
end
for j = 1 : 5
disp(j);
end
shows
1
5
1
2
3
4
5
as expected. And I'm virtually 100% certain your version would too. What version do you have? I'd have to see a screenshot of you running the above code and getting something different to believe otherwise.
Anyway, Star corrected your two errors, one in constructing j and one in constructing qv.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!