doPCA.m 562 B

12345678910111213141516
  1. function [U, S, V, variances, pcaCoords, dataReduced] = doPCA(data)
  2. % This uses other function than the matlab default. Data has samples in
  3. % rows and variables in columns.
  4. % For reproducible results.
  5. rand('seed', 4);
  6. % PCA of centered data. Here 20 components only.
  7. [U, S, V] = pca(data - mean(data), 20);
  8. % Calculate explained variances.
  9. variances = diag(S).^2 / (size(U, 1) - 1);
  10. variances = variances / sum(var(data)) * 100;
  11. % Coefficients in PCs.
  12. pcaCoords = U * S;
  13. % Reconstructed data in reduced dimensions.
  14. dataReduced = U * S * V';
  15. end