for loop in matlab

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.m
for index = values
    % code to execute
end
45 chars
4 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.m
for ii = 1:5
    disp(ii)
end
30 chars
4 lines

Output:

main.m
1
2
3
4
5
10 chars
6 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.m
my_array = [1, 2, 3, 4, 5];
for ii = 1:length(my_array)
    disp(my_array(ii))
end
83 chars
5 lines

Output:

main.m
1
2
3
4
5
10 chars
6 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