%% Initial cleanup
clear all;
close all;
clc;

%% Load feature matrix
[~, ~, data] = xlsread('feature_matrix.xlsx', 'data');

%% Extract information
feature_matrix = cell2mat(data(2:end, 6:end));
age = cell2mat(data(2:end, 3));
pd_dur = cell2mat(data(2:end, 4));
updrs_3 = cell2mat(data(2:end, 5));

%% Perform correlation analysis
% 1. Pearson's corr. coeff. (r, p)
% 2. Spearman's corr. coeff. (r, p)
corr_age = zeros(size(feature_matrix, 2), 4);
corr_pd_dur = zeros(size(feature_matrix, 2), 4);
corr_updrs_3 = zeros(size(feature_matrix, 2), 4);

for i = 1:size(feature_matrix, 2)
    feature = real(feature_matrix(:, i));
    
    % Correlate feature <-> age
    [r_pears, p_pears] = corr(feature, age, 'type', 'pearson');
    [r_spear, p_spear] = corr(feature, age, 'type', 'spearman');
    corr_age(i, 1) = r_pears;
    corr_age(i, 2) = p_pears;
    corr_age(i, 3) = r_spear;
    corr_age(i, 4) = p_spear;
    
    % Correlate feature <-> PD duration
    [r_pears, p_pears] = corr(feature, pd_dur, 'type', 'pearson');
    [r_spear, p_spear] = corr(feature, pd_dur, 'type', 'spearman');
    corr_pd_dur(i, 1) = r_pears;
    corr_pd_dur(i, 2) = p_pears;
    corr_pd_dur(i, 3) = r_spear;
    corr_pd_dur(i, 4) = p_spear;
    
    % Correlate feature <-> UPDRS III
    [r_pears, p_pears] = corr(feature, updrs_3, 'type', 'pearson');
    [r_spear, p_spear] = corr(feature, updrs_3, 'type', 'spearman');
    corr_updrs_3(i, 1) = r_pears;
    corr_updrs_3(i, 2) = p_pears;
    corr_updrs_3(i, 3) = r_spear;
    corr_updrs_3(i, 4) = p_spear;
end

%% Prepare the output tables
stats_age = cell(size(feature_matrix, 2) + 1, 5);
stats_age(2:end, 1) = data(1, 6:end).';
stats_age(1, 2:end) = {'r_pears', 'p_pears', 'r_spear', 'p_spear'};
stats_age(2:end, 2:end) = num2cell(corr_age);

stats_pd_dur = cell(size(feature_matrix, 2) + 1, 5);
stats_pd_dur(2:end, 1) = data(1, 6:end).';
stats_pd_dur(1, 2:end) = {'r_pears', 'p_pears', 'r_spear', 'p_spear'};
stats_pd_dur(2:end, 2:end) = num2cell(corr_pd_dur);

stats_updrs_3 = cell(size(feature_matrix, 2) + 1, 5);
stats_updrs_3(2:end, 1) = data(1, 6:end).';
stats_updrs_3(1, 2:end) = {'r_pears', 'p_pears', 'r_spear', 'p_spear'};
stats_updrs_3(2:end, 2:end) = num2cell(corr_updrs_3);

%% Store the tables to *.xlsx
xlswrite('corr_analysis.xlsx', stats_age, 'corr-age');
xlswrite('corr_analysis.xlsx', stats_pd_dur, 'corr-pd_dur');
xlswrite('corr_analysis.xlsx', stats_updrs_3, 'corr-updrs_3');