Do while loop in Matlab

2,047 次查看(过去 30 天)
UTS
UTS 2014-2-9
回答: Marco Ottina ,2022-12-15
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
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.

请先登录,再进行评论。

更多回答(3 个)

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

请先登录,再进行评论。


Marco Ottina
Marco Ottina 2022-12-15
My suggestion is using the following pattern:
canContinue = true;
while canContinue
% do your code here
canContinue = condition_of_the_do_while ; % insert here your condition
end

类别

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!

Translated by