n = 150;
p = 5;
rng(1);
t1 = 3.0 * randn(n,1);
t2 = 2.0 * randn(n,1);
t3 = 0.5 * randn(n,1);
t4 = 0.4 * randn(n,1);
t5 = 0.3 * randn(n,1);
Z = [t1, t2, t3, t4, t5];
theta12 = pi/6;
theta34 = pi/9;
R12 = [ cos(theta12), -sin(theta12), 0, 0, 0;
sin(theta12), cos(theta12), 0, 0, 0;
0, 0, 1, 0, 0;
0, 0, 0, 1, 0;
0, 0, 0, 0, 1 ];
R34 = [ 1, 0, 0, 0, 0;
0, 1, 0, 0, 0;
0, 0, cos(theta34), -sin(theta34), 0;
0, 0, sin(theta34), cos(theta34), 0;
0, 0, 0, 0, 1 ];
R = R12 * R34;
mu = [5, -3, 2, 0, 1];
sigma = 0.15;
X = Z * R + mu + sigma * randn(n,p);
Xc = X - mean(X,1);
C = cov(Xc);
[V,D] = eig(C);
[latent, idx] = sort(diag(D), 'descend');
coeff = V(:,idx);
score = Xc * coeff;
explained = 100 * latent / sum(latent);
figure;
scatter(score(:,1), score(:,2), 36, 'filled');
grid on;
xlabel(sprintf('PC1 (%.1f%%)', explained(1)));
ylabel(sprintf('PC2 (%.1f%%)', explained(2)));
title('PCA score plot');