gistlib
To calculate mean and standard deviation using for loops in MATLAB, you can follow these steps:
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 chars30 lines
% 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)])
Output:
main.mMean: 3 Standard deviation: 1.5811 35 chars3 lines
Mean: 3 Standard deviation: 1.5811
gistlibby LogSnag