MATLAB Loops (original) (raw)

Last Updated : 27 Jul, 2022

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.

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

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_variable = 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