% M E 345 Class Example Problem - Correlation
% 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 = 'Class_Example_Correlation.xls';
sheet_number = 1;
data_range_1 = 'C5:C12';
data_range_2 = 'D5:D12';
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('Here, r_xy = %g\n',r_xy); % display correlation coefficient

% scatter plot of del_P vs x
figure(1)
hold on;
plot(x,del_P,'o','MarkerFaceColor','w')
ylim([0 0.9])
xlabel('\itx','FontWeight','Bold')
ylabel('\Delta\itP','FontWeight','Bold')
grid on;
hold off;

