pca1.m 985 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. function [signals, PC, V, data] = pca1(data)
  2. % PCA1: Perform PCA using covariance.
  3. %
  4. % Usage:
  5. % [signals, PC, V] = pca1(data)
  6. %
  7. % data (in) - MxN matrix of input data
  8. % (M dimensions, N trials)
  9. % signals - MxN matrix of projected data
  10. % PC - each column is a principal component
  11. % V - Mx1 matrix of variances
  12. % data (out) - mean subtracted data.
  13. %
  14. % From Jon Schlens PCA tutorial.
  15. [M, N] = size(data);
  16. % subtract off the mean for each dimension
  17. mn = mean(data,2);
  18. data = data- repmat(mn,1,N);
  19. % calculate the covariance matrix
  20. covariance = 1/(N-1)*data*data';
  21. if (isnan(covariance))
  22. covariance(:,:) = 0
  23. end
  24. % find the eigenvectors and eigenvalues
  25. [PC, V] = eig(covariance);
  26. % extract diagonal of matrix as vector
  27. V = diag(V);
  28. % sort the variances in decreasing order
  29. [junk, rindices] = sort(-1*V);
  30. V = V(rindices);
  31. PC = PC(:, rindices);
  32. % project the original data set
  33. signals = PC'*data;