In MATLAB, the for loop is used to iterate over a sequence of values, such as an array, and execute the same code for each element in the sequence. The basic syntax of a for loop in MATLAB is as follows:
main.m45 chars4 lines
Here, index is a loop variable that takes on each value in the sequence values. The code inside the loop is executed once for each value of index. For example, the following code iterates over the values 1 to 5 and prints each value:
main.m30 chars4 lines
Output:
main.m10 chars6 lines
In this example, ii is the loop variable, and it takes on the values 1, 2, 3, 4, and 5 in each iteration of the loop. The disp function is used to print each value of ii.
You can also use a for loop to iterate over the elements in an array by combining the loop syntax with the numel and length functions. For example:
main.m83 chars5 lines
Output:
main.m10 chars6 lines
In this example, the loop variable ii iterates over the values 1 to 5, which correspond to the index values of each element in my_array. The disp function is used to print the value of each element in the array.
gistlibby LogSnag