a for loop that calculates average in matlab

You can calculate the average using for loop in Matlab as follows:

main.m
% input vector
vec = [2,4,6,8,10];

% initialize sum variable 
s = 0;

% for loop to calculate sum
for i = 1:length(vec)
    s = s + vec(i);
end

% calculate average
avg = s / length(vec);

% display the result
disp(avg)
221 chars
17 lines

The output will be 6. However, Matlab provides a built-in function mean to calculate the average of a vector, which is a more efficient and quicker way to do this task.

related categories

gistlibby LogSnag