MATLAB Answers

Do while loop in Matlab

2,474 ビュー (過去 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 件のコメント

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

Sign in to comment.

採用された回答

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 件のコメント

UTS
UTS 2014 年 2 月 9 日
Thank you very much,
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.

Sign in to comment.

その他の回答 (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 件のコメント

Timothy Mathias
Timothy Mathias 2018 年 11 月 29 日
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
Seyedeh Razieh Hosseini 2019 年 1 月 5 日
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 2020 年 5 月 1 日
How so? Since do always starts out as true, you only have to write out the calculation once?

Sign in to comment.


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

Sign in to comment.

タグ


Translated by