function loop in matlab

In Matlab, we can define a function that contains a loop to perform a specific task repeatedly. Here is a simple example of a function that uses a loop:

main.m
function [result] = loopFunction(n)
% This function takes a single input argument n, and returns the sum of all
% integers from 1 to n

result = 0; % initialize the result to 0
for i = 1:n % start the loop at 1, and go up to n
    result = result + i; % add the current iteration variable i to the result
end
end
313 chars
10 lines

In this example, we use the for loop to iterate over a range of values. The loop starts at 1, and goes up to n. In each iteration of the loop, we add the current value of i to the result variable. Once the loop is complete, we return the final value of result.

To call this function and get the sum of all integers from 1 to 10, for example, we can simply type:

main.m
>> loopFunction(10)
ans =
    55
33 chars
4 lines

This will return the value result, which is the sum of all integers from 1 to 10.

gistlibby LogSnag