% Example of Principal Component Analysis
% On OECD economic data dataset
categories={'Income' 'Agriculture' 'Industry' 'Service'};
%%
% Get a first quick impression about the data
boxplot(oecd)
% You could also use 'plot' to compare pairs of variables,

%%
% Get a quick idea of correlations
corr(oecd)
%%
% We need to standardize the data
% Divide the data by the corresponding standard deviations
stdr = std(oecd);
sr = oecd./repmat(stdr,20,1);
% The standardized rankings are now in variable 'sr'
boxplot(sr)
%%
% Now find the principal components!
[coefs,scores,variances,t2] = princomp(sr);
%%
% First, look at vectors of principal component coefficients
coefs
% The first column is the first principal component
% Note the weights of different factors
%%
% Component scores (variable 'scores') are the original data
% mapped into the new variables
% Projection on the first two (most significant) principal components:
plot(scores(:,1),scores(:,2),'+')
xlabel('1st Principal Component');
ylabel('2nd Principal Component');
% Note the outlying points
%%
gname

%%
% Using the 'variances' output, calculate the percent of variance
% in the data explained by each principal component
percent_explained = 100*variances/sum(variances)
pareto(percent_explained)
xlabel('Principal Component')
ylabel('Variance Explained (%)')

%%
% Visualize the results of the principal component analysis
biplot(coefs(:,1:2), 'scores',scores(:,1:2),... 
'varlabels',categories);
% Each of the variables is represented in this plot by a vector, and
% the direction and length of the vector indicates how each variable 
% contributes to the two principal components in the plot.
%axis([-.26 1 -.51 .51]);

