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.
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
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
We want to find
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
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.
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
To call the function, the user should use the following
Feel free to drop your code in the comment section.