% ME 345 Class Example Problem - Linear Regression
% Barukyah Shaparenko and John M. Cimbala

clear all
close all

% Import data from Excel
% NOTE: Excel data file must reside in same folder as Matlab m-file
% Use xlsread or xlsxread

xls_filename = 'Regression_linear_fit.xls';
sheet_number = 1;
data_range_1 = 'B6:B13';
data_range_2 = 'C6:C13';
x = xlsread(xls_filename,sheet_number,data_range_1); % mm
del_P = xlsread(xls_filename,sheet_number,data_range_2); % kPa

% The linear correlation coefficient r_xy is calculated, as shown below:
% r_xy corresponds to Multiple R in Excel

% calculate means
x_bar = mean(x); % average x
del_P_bar = mean(del_P); % average del_P

% calculate sums
sum_x = sum((x-x_bar).^2); % sum of x data squared
sum_del_P = sum((del_P-del_P_bar).^2); % sum of del_P data squared
sum_cross_terms = sum((x-x_bar).*(del_P-del_P_bar)); % sum of cross terms in numerator

r_xy = sum_cross_terms/sqrt(sum_x*sum_del_P); % formula for correlation coefficient

fprintf('\n----------------------\n');
fprintf('Multiple R \t%g\n',r_xy);

% To perform regression analysis in Matlab, use left-divide '\'
% The column of ones allows Matlab to solve for a y-intercept.

X = [ones(length(x),1) x];
b = X\del_P;

fprintf('\nIntercept \t\t%g\n',b(1));
fprintf('X Variable 1 \t%g\n',b(2));

% To plot the best-fit straight line, 
% we create data points using the equation 
% for the best-fit straight line:

del_P_fit = b(1) + b(2)*x;

% Finally, we plot this line on the same plot
% as the data points for comparision - see accompanying plot.

% scatter plot of del_P vs x with best-fit straight line
figure(1)
hold on;
plot(x,del_P,'bo','MarkerFaceColor','w') % data points
plot(x,del_P_fit,'r-','LineWidth',2.5) % best-fit straight line
legend('Data points','Best-fit straight line','Location','Best')
ylim([0 0.9])
xlabel('\itx','FontWeight','Bold')
ylabel('\Delta\itP','FontWeight','Bold')
grid on;
hold off;
