4 loop in matlab

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.m
for index = values
    % code block to be executed
end
55 chars
4 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.m
for i = 1:5
    sq = i^2;
    disp(sq)
end
43 chars
5 lines

This will output:

main.m
1
4
9
16
25
12 chars
6 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.m
a = [1 2 3 4 5];
for i = a
    disp(i)
end
43 chars
5 lines

This will output:

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

related categories

gistlibby LogSnag