% Example Problem in MatLab - Errors and Uncertainties
% Barukyah Shaparenko and John M. Cimbala

clear all
close all

% Import data from Excel
% Save Excel data in same folder as Matlab m-file
% Use xlsread or xlsxread

% sheet_number and data_range are optional
% Default is Sheet 1 with all (numerical) data imported

% xls_filename = 'Sample_Excel_error_calculations.xls';
% sheet_number = 1;
% data_range = 'A5:A10';
% T = xlsread(xls_filename,sheet_number,data_range);
% T_true = xlsread(xls_filename,sheet_number,'C14');

% Alternate way to read in data manually (without using Excel file):
T = [22.15; 22.22; 22.09; 22.21; 22.18; 22.24];
T_true = 22.10;

n = length(T); % Number of data points in this sample
disp([' ']);
disp(['n = ' num2str(n)]);
T_avg = mean(T(1:end)); % Average of all readings
disp(['T_avg = ' num2str(T_avg)]);

bias = T_avg - T_true; % bias error, T_avg - T_true
disp(['Bias error = ' num2str(bias)]);

Sum = 0;
for i=1:n
	del_T_true(i) = T(i) - T_true; % T - T_true
	del_T_avg(i) = T(i) - T_avg; % T - T_avg
	Sum = Sum + (T(i) - T_true);
end

MBE = Sum/n/T_true; % Mean Bias Error
disp(['MBE = ' num2str(MBE)]);
MBE_percent = MBE*100; % Mean Bias Error, percent
disp(['MBE = ' num2str(MBE_percent) '%']);


% Basic statistics for this data set:

n = length(T);
sum_3 = 0;
sum_4 = 0;
for i = 1:n
  del_T_avg(i) = T(i) - mean(T);
  sum_3 = sum_3 + del_T_avg(i)^3;
  sum_4 = sum_4 + del_T_avg(i)^4;
end
  
Mean = mean(T);
Standard_Error = std(T)/sqrt(n);
Median = median(T);
Mode = mode(T);
Standard_Deviation = std(T);
Sample_Variance = Standard_Deviation^2;
Kurtosis = n*(n+1)/(n-1)/(n-2)/(n-3)*sum_4/Standard_Deviation^4 - 3*(n-1)^2/(n-2)/(n-3);
Skewness = n/(n-1)/(n-2)*sum_3/Standard_Deviation^3;
Range = max(T) - min(T);
Minimum = min(T);
Maximum = max(T);
Sum = sum(T);
Count = length(T);

fprintf('\n')
fprintf('Mean \t\t\t\t%g\n',Mean);
fprintf('Standard Error \t\t%g\n',Standard_Error);
fprintf('Median \t\t\t\t%g\n',Median);
fprintf('Mode \t\t\t\t%g\n',Mode);
fprintf('Standard Deviation \t%g\n',Standard_Deviation);
fprintf('Sample Variance \t%g\n',Sample_Variance);
fprintf('Kurtosis \t\t\t%g\n',Kurtosis);
fprintf('Skewness \t\t\t%g\n',Skewness);
fprintf('Range \t\t\t\t%g\n',Range);
fprintf('Minimum \t\t\t%g\n',Minimum);
fprintf('Maximum \t\t\t%g\n',Maximum);
fprintf('Sum \t\t\t\t%g\n',Sum);
fprintf('Count \t\t\t\t%g\n',Count);
