how to perform principal component analysis in matlab

To perform principal component analysis in Matlab, you can use the built-in function pca. Here is an example usage:

main.m
% create a sample data matrix
X = randn(100, 5);

% perform PCA on the data
[coeff, score, latent, tsquared, explained] = pca(X);

% display the coefficients (eigenvectors)
disp('Coefficients (Eigenvectors):');
disp(coeff);

% display the scores (projection of original data onto principal component axes)
disp('Scores (Projection of data onto principal component axes):');
disp(score);

% display the eigenvalues (variances explained by each principal component)
disp('Eigenvalues (Variances explained by each principal component):');
disp(latent);

% display the squared Mahalanobis distances of each observation from the center of the data
disp('Squared Mahalanobis Distances:');
disp(tsquared);

% display the percentage of total variance explained by each principal component
disp('Percentage of Variance Explained:');
disp(explained);
841 chars
26 lines

Note that coeff contains the principal component coefficients (eigenvectors), score contains the projected data onto the principal component axes, and latent contains the eigenvalues of the covariance matrix of the data.

You can also use the pcares function to perform PCA with data scaling and centering, and the pcaresplot function to visualize the results of PCA.

main.m
% create a sample data matrix
X = randn(100, 5);

% perform PCA on the data with scaling and centering
[score, coeff, latent, tsquared, explained] = pcares(X);

% display the scores (projection of original data onto principal component axes)
disp('Scores (Projection of data onto principal component axes):');
disp(score);

% plot the scree plot
pcaresplot(latent, explained);
377 chars
13 lines

related categories

gistlibby LogSnag