MATLAB Answers

Do while loop in Matlab

조회 수: 4,383(최근 30일)
UTS
UTS 2014년 2월 9일
댓글: David Michelman 2020년 5월 1일
Could you please let me know the Matlab code that is similar to C++ code as shown below:
do {
<your calculations>
} while (abs(A - B) <= 50)
Thanks
  댓글 수: 2
MathWorks Support Team
MathWorks Support Team 2018년 11월 27일
We updated the question to reflect correct syntax

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

채택된 답변

Mischa Kim
Mischa Kim 2014년 2월 9일
편집: MathWorks Support Team 2018년 11월 27일
There is no 1-to-1 correspondence to the C++ do while loop in MATLAB. Your best option is to use a while loop. The difference is that while loops check the condition at the beginning of the loop while do while loops check the condition at the end of the loop.
while (abs(A-B) <= 50)
...
end
To check the condition at the end of the loop using a while loop, use an if statement inside the while loop:
while 1
<your calculations>
if ~(abs(A - B) <= 50)
break;
end
end
  댓글 수: 2
Image Analyst
Image Analyst 2014년 2월 9일
Please mark his answer as "Accepted" so we know that we don't need to look at it anymore and he gets credit for it.

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

추가 답변(2개)

Jos (10584)
Jos (10584) 2014년 2월 9일
A do-while loop in disguise:
while true
% statements here
% if ~WhileCondition, break ; end
end
or
  댓글 수: 3
David Michelman
David Michelman 2020년 5월 1일
How so? Since do always starts out as true, you only have to write out the calculation once?

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


Vigneshwar Pesaru
Vigneshwar Pesaru 2017년 9월 17일
Hi!!!
There is no 'do while' loop in MATLAB in fact you can perform the similar action using 'while' which is powerful in MATLAB
  댓글 수: 1
P Richards
P Richards 2019년 7월 23일
IHMO The absence of do while makes some coding more difficult than it needs to be:
do
theConditionStillExists=attemptToFixIt();
while theConditionStillExists

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by