create a for loop in matlab

A basic for loop in MATLAB can be created using the following syntax:

main.m
for i = 1:n
    % code to be executed in each iteration
end
60 chars
4 lines

In this loop, i is the loop variable that takes integer values from 1 to n. The code block inside the loop will be executed n times, with i incremented by 1 in each iteration.

For example, the following code calculates the sum of integers from 1 to 10 using a for loop:

main.m
sum = 0;
for i = 1:10
    sum = sum + i;
end
disp(sum); % output: 55
69 chars
6 lines

In this code, the loop runs 10 times, with i taking values from 1 to 10. The variable sum is initialized to 0 before the loop starts, and in each iteration, the value of i is added to sum. After the loop, the value of sum is printed to the console using the disp function.

gistlibby LogSnag