In Matlab, a for loop is used when you want to execute a statement or a series of statements repeatedly, for a specific number of times. The basic syntax of a for loop is as follows:
main.m38 chars4 lines
Here, index
is the loop variable, and values
is the set of values that the loop variable will take during each iteration. The statements
inside the loop will be executed for each value of index
.
For example, the following code shows how to use a for loop to compute the factorial of a number:
91 chars6 lines
In this code, the loop variable i
takes the values 1
, 2
, 3
, 4
, and 5
during each iteration of the loop. The statement fact = fact * i
multiplies the current value of fact
by the current value of i
, and stores the result back in fact
.
After the loop completes, the variable fact
will contain the factorial of n
(which in this case is 120
, since 5! = 5*4*3*2*1 = 120
).
gistlibby LogSnag