A for loop is a useful programming construct to execute repetitive code blocks. The syntax for a for loop in MATLAB is as follows:
main.m55 chars4 lines
Here, index is the loop variable, which takes values from the values vector/matrix. The code block inside the loop is executed for each value of the index.
For example, suppose we want to compute the squares of the numbers from 1 to 5. We can use a for loop in MATLAB as follows:
main.m43 chars5 lines
This will output:
main.m12 chars6 lines
Here, the loop variable i takes values from 1 to 5 (inclusive), and for each value of i, the square of i is computed and displayed using disp() function.
Note that we can also use a for loop to iterate over the elements of a vector/matrix. We can do this as follows:
main.m43 chars5 lines
This will output:
main.m10 chars6 lines
Here, the loop variable i takes values from the elements of a, and for each value of i, it is displayed using disp() function.
gistlibby LogSnag