MATLAB Answers

Do while loop in Matlab

조회 수: 3,009(최근 30일)
UTS
UTS 9 Feb 2014
Commented: P Richards 23 Jul 2019
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

Jan
Jan 9 Feb 2014
This is no valid C++syntax. Do you mean:
do {
<your calculations>
} while (abs(A - B) <= 50)
MathWorks Support Team
We updated the question to reflect correct syntax

로그인 to comment.

채택된 답변

Mischa Kim
Mischa Kim 9 Feb 2014
MathWorks Support Team 님이 편집함. 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

UTS
UTS 9 Feb 2014
Thank you very much,
Image Analyst
Image Analyst 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.

로그인 to comment.

More Answers (2)

Jos (10584)
Jos (10584) 9 Feb 2014
A do-while loop in disguise:
while true
% statements here
% if ~WhileCondition, break ; end
end
or

  댓글 수: 2

Timothy Mathias
Timothy Mathias 29 Nov 2018
Nice idea Jos. I modified it a bit for my particular needs.
do = true;
while do
% statements here
% do = result_of_conditions_test;
end
Seyedeh Razieh Hosseini
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?

로그인 to comment.


Vigneshwar Pesaru
Vigneshwar Pesaru 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

P Richards
P Richards 23 Jul 2019
IHMO The absence of do while makes some coding more difficult than it needs to be:
do
theConditionStillExists=attemptToFixIt();
while theConditionStillExists

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

태그


Translated by