Do while loop in Matlab

1.370 Ansichten (letzte 30 Tage)
UTS
UTS am 9 Feb. 2014
Beantwortet: Marco Ottina am 15 Dez. 2022
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 Kommentare
Jan
Jan am 9 Feb. 2014
This is no valid C++syntax. Do you mean:
do {
<your calculations>
} while (abs(A - B) <= 50)
MathWorks Support Team
MathWorks Support Team am 27 Nov. 2018
We updated the question to reflect correct syntax

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Mischa Kim
Mischa Kim am 9 Feb. 2014
Bearbeitet: MathWorks Support Team am 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
<your calculations>
if ~(abs(A - B) <= 50)
break;
end
end
  2 Kommentare
UTS
UTS am 9 Feb. 2014
Thank you very much,
Image Analyst
Image Analyst am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (3)

Jos (10584)
Jos (10584) am 9 Feb. 2014
A do-while loop in disguise:
while true
% statements here
% if ~WhileCondition, break ; end
end
or
  3 Kommentare
Seyedeh Razieh Hosseini
Seyedeh Razieh Hosseini am 5 Jan. 2019
The problem here is that you have to calculate twice. our calculation have to be done once before the loop and again inside the loop. that leads to repetition of a part of a code. what should we do in such a case?
David Michelman
David Michelman am 1 Mai 2020
How so? Since do always starts out as true, you only have to write out the calculation once?

Melden Sie sich an, um zu kommentieren.


Marco Ottina
Marco Ottina am 15 Dez. 2022
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

Vigneshwar Pesaru
Vigneshwar Pesaru am 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
  1 Kommentar
P Richards
P Richards am 23 Jul. 2019
IHMO The absence of do while makes some coding more difficult than it needs to be:
do
theConditionStillExists=attemptToFixIt();
while theConditionStillExists

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by