Basically there is no do while loop in Matlab like c programming, cpp programming, and other programming languages. But instead of using do while loop works powerfully in Matlab. In Matlab, mostly two loops are used to do operations. If we are sure about how many times we need to perform a particular task then for loop is used. And if we are not sure about how many times we want to perform a particular task then while loop is used. Inside the loop, we can write condition and repetition statements of particular programs and increment/decrement of variables.
The syntax used to write while loop in the program is ‘while’ command and at the end, we need to write ‘end’ command to stop the loop.
How do while loop works in Matlab?
To write while loop in Matlab always we need to consider three parameters.
- The first condition limits the loop at the time of execution.
- Second parameter statements mean what is actually expected output.
- Th third parameter is the incrementing loop variable. If we missed the increment line then the loop will execute infinite times.
while(condition) Statement1 Statement2 . . Statement n Increment loop variable syntax
Examples of do while loop in Matlab
Given below are the examples of do while loop in Matlab:
In this example let us consider one variable a. The initial value assigned to a is 2. After applying condition ( a < = 5) along with while loop, loop will execute for values 2, 3, 4, 5. And here statement just displays the value of a. Therefore it will display output as 2, 3, 4, 5.
a = 2 while(a <= 5) disp(a) a = a + 1; end
The second example is a square function. In this example, we are going to find out the square of values till 5. Here var is the variable name. The value assigned to var is 1 so that var will vary from 1 to 5.
var = 1 while(var <=5) op=var*var; disp(op) var = var + 1; end
In this example there are two different operations, one is even numbers and the second is odd numbers. To find out even and odd numbers we have used two different while loops.
var = 0 disp('even numbers') while(var <= 10) disp(var) var = var + 2; end var = 1 disp('odd numbers') while(var <= 10) disp( var ) var = var + 2 ; end
In previous examples, we start the problem from the origin, but by using a while loop we can change the range of problems. In this example, we consider numbers from 41 to 65. Here we have used two variables. Var is used for start and end at is used for the end of the range.
% even numbers between 41 to 65 var = 40 endat = 65 disp('even numbers') while(var <= 65) disp( var ) var = var + 2; end var = 41 disp('odd numbers') while(var <= endat) disp( var ) var = var + 2 ; end
By using a while loop we can create various number series and applications. In this example, we created a series of numbers by considering output previous iterations.
% addition of previous numbers var = 0 endat= 10 op = 0 disp('number series ') while(var <= endat) %disp(var); op = op + var var = var + 1 ; end