Why is Q=30 after the loop is ran?

1 view (last 30 days)
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

Accepted Answer

Les Beckham
Les Beckham on 4 Aug 2022
Edited: Les Beckham on 4 Aug 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 Comments
Steven Lord
Steven Lord on 4 Aug 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!