calculate mean, standard deviation and coefficient of variation using for loops in matlab

The mean, standard deviation and coefficient of variation can be computed using for loops in MATLAB by first calculating the sum of the elements and the total number of elements in the array. Here is an example:

main.m
% initialize a sample array
x = [1 2 3 4 5];

% calculate the sum and number of elements of the array
n = length(x);
sum_x = 0;
for i = 1:n
    sum_x = sum_x + x(i);
end

% calculate the mean
mean_x = sum_x / n;

% calculate the standard deviation
sum_squared_diff = 0;
for i = 1:n
    squared_diff = (x(i) - mean_x)^2;
    sum_squared_diff = sum_squared_diff + squared_diff;
end
std_dev_x = sqrt(sum_squared_diff / (n-1));

% calculate the coefficient of variation
cv_x = std_dev_x / mean_x * 100;

% print the results
fprintf('Mean: %.2f\n', mean_x);
fprintf('Standard Deviation: %.2f\n', std_dev_x);
fprintf('Coefficient of Variation: %.2f%%\n', cv_x);
656 chars
29 lines

In this example, we loop through each element of the array to calculate the sum of the elements and the squared difference of each element from the mean. We then calculate the mean, standard deviation and coefficient of variation using the formulas:

mean_x = sum_x / n

std_dev_x = sqrt(sum((x - mean_x)^2) / (n-1))

cv_x = std_dev_x / mean_x * 100

Note that the denominator for the standard deviation calculation is (n-1) instead of n to correct for the bias due to using the same data to estimate both the mean and the deviations.

gistlibby LogSnag