calculate mean and standard deviation using for loops in matlab

To calculate mean and standard deviation using for loops in MATLAB, you can follow these steps:

  1. Define a vector of data for which you want to calculate the mean and standard deviation.
  2. Initialize variables for the sum and number of data points.
  3. Use a for loop to iterate over the data vector and calculate the sum and number of data points.
  4. Calculate the mean by dividing the sum by the number of data points.
  5. Use another for loop to iterate over the data vector and calculate the squared difference from the mean.
  6. Calculate the sum of the squared differences.
  7. Calculate the variance by dividing the sum of the squared differences by the number of data points minus one.
  8. Calculate the standard deviation by taking the square root of the variance.

Here's an example code that implements these steps:

main.m
% define data vector
data = [1 2 3 4 5];

% initialize variables
sum_data = 0;
num_data = length(data);
sum_squared_diff = 0;

% calculate sum and number of data points
for i = 1:num_data
    sum_data = sum_data + data(i);
end

% calculate mean
mean_data = sum_data / num_data;

% calculate variance
for i = 1:num_data
    squared_diff = (data(i) - mean_data)^2;
    sum_squared_diff = sum_squared_diff + squared_diff;
end
var_data = sum_squared_diff / (num_data - 1);

% calculate standard deviation
std_data = sqrt(var_data);

% display results
disp(['Mean: ', num2str(mean_data)])
disp(['Standard deviation: ', num2str(std_data)])
634 chars
30 lines

Output:

main.m
Mean: 3
Standard deviation: 1.5811
35 chars
3 lines

related categories

gistlibby LogSnag