www.pudn.com > snippets(1).rar > learn_pca.m, change:2009-10-12,size:944b


function [B,pca] = learn_pca(A,Globals,flow_flag)
%
% learn a PCA basis from training matrix, and project the matrix

[m,n] = size(A);

if flow_flag
  preserve = Globals.pca_preserve_flow;
else
  preserve = Globals.pca_preserve_form;
end

% center data
shift = mean(A,2);
for u = 1:n
  A(:,u) = A(:,u)-shift;
end

% perform svd
[V,D,U] = svd(A,0);
d = diag(D);

% find required number of basis vectors
frac = cumsum(d/sum(d));
if preserve>0
  num = find(frac>preserve,1);
  if Globals.DISPLAY, fprintf('(%d dim/%2.0f%% var)..',num,100*preserve); end
else
  num = -preserve;
  if Globals.DISPLAY, fprintf('(%d dim/%2.0f%% var)..',num,round(100*frac(num))); end
end

% length normalization
if Globals.pca_normalize

  for u = 1:n
    A(:,u) = A(:,u)/norm(A(:,u));
  end
  pca.normalized = 1;

else

  pca.normalized = 0;
 
end

% project training data
basis = V(:,1:num)';
B = basis*A;

% return basis info
pca.shift = shift;
pca.basis = basis;