Why is Q=30 after the loop is ran?

조회 수: 2 (최근 30일)
Allison Sims
Allison Sims 2022년 8월 4일
댓글: Steven Lord 2022년 8월 4일
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

채택된 답변

Les Beckham
Les Beckham 2022년 8월 4일
편집: Les Beckham 2022년 8월 4일
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
Les Beckham
Les Beckham 2022년 8월 4일
You are quite welcome.
Steven Lord
Steven Lord 2022년 8월 4일
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by