%Create 3D cloud of data points, then do pca on it clc; disp('3D PCA analysis'); CorXY = input('Correlation between X & Y values: '); CorXZ = input('Correlation between X & Z values: '); for K = 1:100; X = 10*randn; Y = CorXY*X + (1 - CorXY)*7*randn; Z = CorXZ*X + (1 - CorXZ)*5*randn; Dta(K, :) = [X, Y, Z]; end; CVAR = cov(Dta) CCF = corrcoef(Dta); [V, Ev] = eig(CVAR) Variance = flipud(diag(Ev)/sum(diag(Ev))) CumulativeVariance = cumsum(Variance) PC1 = V(:, 3)*[44, -30]; PC2 = V(:, 2)*[44, -30]; figure(1); P1 = plot(Dta(:, 1), Dta(:, 2), 'or'); axis equal; figure(2); P2 = plot(Dta(:, 1), Dta(:, 2), 'or', PC1(1, :), PC1(2, :), 'k-', PC2(1, :), PC2(2, :), 'k--'); axis equal; title('Solid line = PC1, Dashed line = PC2'); set(P1, 'linewidth', 2); set(P2, 'linewidth', 2); figure(3); P3D = scatter3(Dta(:, 1), Dta(:, 2), Dta(:, 3), 'or', 'fill'); line(PC1(1, :), PC1(2, :), PC1(3, :), 'linewidth', 3, 'color', 'k'); line(PC2(1, :), PC2(2, :), PC2(3, :), 'linewidth', 3, 'color', 'b', 'linestyle', '--'); rotate3d on;