Why is Q=30 after the loop is ran?

2 visualizaciones (últimos 30 días)
Allison Sims
Allison Sims el 4 de Ag. de 2022
Comentada: Steven Lord el 4 de Ag. de 2022
B=1;
Q=0;
if B==1 && Q~=B
Q=20;
if B<0 || Q==20
Q=30;
end
elseif B<10
Q=40;
else
Q=50;
end
disp(Q)
30
%How do I trace the loop I thought Q would equal 20 after the first condition was met

Respuesta aceptada

Les Beckham
Les Beckham el 4 de Ag. de 2022
Editada: Les Beckham el 4 de Ag. de 2022
B=1;
Q=0;
if B==1 && Q~=B
Q=20;
if B<0 || Q==20 % you just set Q equal to 20 on the line above so this condition is true
Q=30;
end
elseif B<10
Q=40;
else
Q=50;
end
disp(Q)
30
Perhaps you meant to do this?
B=1;
Q=0;
if B==1 && Q~=B
Q=20;
elseif B<0 || Q==20
Q=30;
elseif B<10
Q=40;
else
Q=50;
end
disp(Q)
20
Issues like this are easier to find if you indent your code properly. In the Matlab editor, do Ctrl-A to select all of the code and then Ctrl-I to automatically indent it. Then you would have seen that that second if test was inside the first one.
  3 comentarios
Les Beckham
Les Beckham el 4 de Ag. de 2022
You are quite welcome.
Steven Lord
Steven Lord el 4 de Ag. de 2022
Another useful technique to understand what the code is doing is to set a breakpoint on one of the lines of code (in this case I'd probably set it on the line immediately before the if statement.) When you run your code and MATLAB reaches the breakpoint, it will enter debug mode.
You can then step through the code line by line using the Step icon in the Run section of the Editor tab of the toolstrip, run multiple lines by using the Run to Here button (see the second section on this documentation page), or tell MATLAB to quit debugging.
If you run your original code step-by-step you'll see that it goes right from the line that starts the body of the first if statement directly to the second if statement. If you run the modified code provided by @Les Beckham it will skip directly over the elseif statements and the else statement.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by