Simplicity
Simplicity

Reputation: 48956

Is there a way to perform a do-while?

I'm planning to use a do-while loop in MATLAB.
Is there a way to do that?

Upvotes: 16

Views: 25444

Answers (4)

Cris Luengo
Cris Luengo

Reputation: 60761

MATLAB does not have a do-while construct (nor a do-until construct, in MATLAB the condition is always at the top of the loop). But you can always easily rewrite a do-while construct to a while-do construct.

For example, say you have a loop that iterates a computation until convergence. It is written as a do-while construct as follows:

result = 0
do
   new_result = ...
   difference = abs(new_result - result)
   result = new_result
while difference > tol

You can write exactly the same thing with a while-do loop as follows:

result = 0
difference = Inf
while difference > tol
   new_result = ...
   difference = abs(new_result - result)
   result = new_result
end

The only extra thing we needed to do was initialize difference to a value that guarantees that the loop runs at least once.

This is similar to EHB's answer in that they also converted the do-while construct into a while-do construct. But in general it is not necessary to create a separate sentinel variable to do so.

Upvotes: -1

EBH
EBH

Reputation: 10450

Here's another option in MATLAB (closer to a do-while syntax):

do = true;
while(do || condition)
    do = false;
    % things to do...
end

Upvotes: 3

winkmal
winkmal

Reputation: 632

At least, Octave has do-until. This example creates a variable fib that contains the first ten elements of the Fibonacci sequence.

fib = ones (1, 10);
i = 2;
do
  i++;
  fib (i) = fib (i-1) + fib (i-2);
until (i == 10)

Of course, you must invert your abortion condition compared to do-while.

Upvotes: 1

Abhishek Thakur
Abhishek Thakur

Reputation: 17025

while(true)

%code

    if condition==false
        break; 
    end 
end

Upvotes: 28

Related Questions