Related Articles

# MATLAB – Loops

• Difficulty Level : Expert
• Last Updated : 13 May, 2021

MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces.

• While Loop: While loop works same as it does in other common languages like python, java etc. But here syntax varies from language to language. While loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.

Syntax:

```while expression
statements
end```

Example 1:

## Matlab

 `%MATLAB code to illustrate` `%for loop` `count=0;` `while` `(count < 3)   ` `   ``fprintf(``'Hello From GeekforGeeks\n'``);` `   ``count=count+1;` `end`

Output:

```Hello From GeekforGeeks
Hello From GeekforGeeks
Hello From GeekforGeeks```
• For Loop: For loops are used for sequential traversal. As syntax varies from language to language. Let us learn how to use for loop for sequential traversals.

Syntax:

```for initial value:step value:final value
statements
end```

or

```for initial value:final value
statements
end ```

Example 2

## Matlab

 `%MATLAB code to illustrate` `%for loop` `for` `i = 1:5` `   ``fprintf(``'%d '``,i)` `end`

Output:

`1 2 3 4 5`

Example 3

## Matlab

 `%MATLAB code to illustrate` `%for loop` `for` `i = 1:2:5` `   ``fprintf(``'%d '``,i)` `end`

Output:

`1 3 5`

We have one more way of using for loop, that is used to access array elements. Here we assign an array directly to the for loop to access its elements through the iterator variable (i.e., i or j etc).

Example 4

## Matlab

 `%for iterator_vairable = array` `for` `i =[1 2 3 4]` `   ``fprintf(``'%d '``,i)` `end`

Output:

`1 2 3 4`

Iterating through strings is same as iterating through a range of numbers. Here we use length() function to provide final value in for loop, and we can also use disp() function to print the output.

Example 5

## Matlab

 `%MATLAB code to illustrate` `%how to iterate through strings` `String = ``'GeeksforGeeks'` `for` `i = 1:length(String)` `   ``fprintf(``'%c '``,String(i))` `   ``%disp(String(i))` `end`

Output:

`G e e k s f o r G e e k s`

My Personal Notes arrow_drop_up