For loop in Matlab

Working and constructing for loops in Matlab happen the exact same way they do in other programing languages, at the only difference that in Matlab the first index the for loop goes through is never zero. In Matlab, the first index is 1, and this is an information you should always remember while working with for loops in Matlab.

We have recently used a for loop here, while going through Euler methods in Matlab without spending lot of time on the for loop itself, in this post we will work with the later a little intensively.

For Loop in Matlab

let’s start with the basic design flow of a for loop structure.

for-loop

Image credit: programiz.com

The image above shows you how the loop is set to work. Without spending too much energy in understanding how this work with only the theoretical explanation, let’s test it on some real world examples.

For loop Matlab Example

Example 1

Sum all elements of a vector

In the first example, we just want to sum all elements of a vector

if the vector is the following

matlab-matrix-operation-example

We want to find

for-loop-in-matlab

We want to sum elements in an iterative way. We will create a variable m and at each iteration, we will update it value till reaching the last value of the vector.

The code looks like

sum=0;
A=[7 14 4 3 12 5 0 1];
    for i=1:length(A)
      sum=sum+A(i);
    end;
sum

Example 2

In this example, we will simply find the factorial of a number which we will request from the user.

More explicitly, we want the mini program to ask a number from a user, verify that the number is not negative, and compute its factorial.

The code

numb=input('Enter a number: ');
fact=1;
if numb<0
fprintf('the number you have entered is negative');
else
    for i=1:numb
       fact=fact*i;
    end
fact
end

Example 3

This one is more an exercise than an example. Write a Matlab function that computes the following sum while requesting the value of x and n from the user.

for-loop-in-matlab

To call the function, the user should use the following

for-loop-in-matlab

Feel free to drop your code in the comment section.

tchouken2

Related Posts