%% PCA by decomposition of the covariance matrix
% Size of the data matrix X
[n,p]=size(X);
% Column centering
meanX = mean(X);
X_Centred = X - ones(n,1) * meanX;
% Compute variance-covariance matrix
% for scores
CovM_scores = cov(X_Centred);
% for variables
CovM_loadings = cov(X_Centred');
% Compute eigenvalue & eigenvectors by keeping the matrix form
[V_scores,D_scores] = eig(CovM_scores);
D_scores = fliplr(D_scores);D_scores = flipud(D_scores);
V_scores = fliplr(V_scores);
[V_loadings,D_loadings] = eig(CovM_loadings);
D_loadings = fliplr(D_loadings);D_loadings = flipud(D_loadings);
V_loadings = fliplr(V_loadings);
% Compute of total variance of the dataset: TotalVP
TotalVP = trace(D_scores);
% Compute the percentage of variance explained by each principal
%component
Pourcentages = {};
for i=1:size(D_scores,1)
    Perrcentages{i,1} = strcat('PC',num2str(i));
    Perrcentages{i,2} = num2str(D_scores(i,i)/TotalVP*100);
end
% Compute factorial coordinates (scores) for each sample point on
% components space
Coord =[];
Coord = X_Cent*V_scores;
% Compute factorial contributions (loadings) for each sample point
% on components space
Contrib =[];
Contrib = X_Cent'*V_loadings;
%% PCA by SVD
% Size of the data matrix X
[n,p]=size(X);
% Column centering
meanX = mean(X);
X_Centred = X - ones(n,1) * meanX;
% Compute scores and loadings simultaneously
[U SingularValues Loadings] = svd(X_Centred);

% Scores T
T = U * SingularValues;