for and end in matlab

In MATLAB, the general syntax for a for loop is:

main.m
for iterator_variable = start_value:step_size:end_value
    % Code to be executed in each iteration
end
104 chars
4 lines

where iterator_variable takes the initial value of start_value and increments by step_size until it reaches end_value.

For example, the following code displays the numbers from 1 to 5:

main.m
for i = 1:5
    disp(i);
end
29 chars
4 lines

The output of this code will be:

main.m
1
2
3
4
5
10 chars
6 lines

The end keyword marks the end of the loop body. All the code that needs to be executed inside the for loop should be between the for statement and the end statement.

Note that MATLAB supports other types of loops, such as while loops or do-while loops, which can be used in different situations.

related categories

gistlibby LogSnag