A for loop can be used in MATLAB to iterate over a set of values, such as a vector or array. The basic syntax of a for loop in MATLAB is as follows:
main.m37 chars4 lines
Where index
is a loop variable that takes on each value in the values
array, and statements
is the code that should be executed during each iteration of the loop.
For example, the following code uses a for loop to iterate over a vector x
, squaring each element and storing the result in a new vector y
:
main.m75 chars7 lines
Output:
main.m16 chars2 lines
A nested for loop has one or more for loops nested inside another for loop. This is often used to iterate over a 2D matrix or array. The basic syntax for a nested for loop is as follows:
main.m73 chars6 lines
Where index1
and index2
are loop variables that take on each value in the values1
and values2
arrays, respectively, and statements
is the code that should be executed during each iteration of the nested loops.
For example, the following code uses a nested for loop to iterate over a 2D matrix A
, calculating the sum of each row and storing the result in a new vector sums
:
main.m184 chars12 lines
Output:
main.m11 chars2 lines
gistlibby LogSnag