# Do while loop in Matlab

2,074 views (last 30 days)
UTS on 9 Feb 2014
Answered: Marco Ottina on 15 Dec 2022
Could you please let me know the Matlab code that is similar to C++ code as shown below:
do {
} while (abs(A - B) <= 50)
Thanks
##### 2 CommentsShowHide 1 older comment
MathWorks Support Team on 27 Nov 2018
We updated the question to reflect correct syntax

Mischa Kim on 9 Feb 2014
Edited: MathWorks Support Team on 27 Nov 2018
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
if ~(abs(A - B) <= 50)
break;
end
end
##### 2 CommentsShowHide 1 older comment
Image Analyst on 9 Feb 2014
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.

Jos (10584) on 9 Feb 2014
A do-while loop in disguise:
while true
% statements here
% if ~WhileCondition, break ; end
end
or
David Michelman on 1 May 2020
How so? Since do always starts out as true, you only have to write out the calculation once?

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

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

### 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!