No Disconnect

Things I’d rather not forget

Principal component analysis in Octave

leave a comment »

% create sample data
matrix = [1 2 3; 4 5 6; 7 8 9; 10 11 12];
matrix = matrix.^2;

matrix = center(matrix); % subtract column means
cv = cov(matrix); % calculate covariance
[v, lambda] = eig(cv); % compute eigenvectors and eigenvalues
[sorteigen, order] = sort(diag(lambda),'descend'); % sort the eigenvalues
v = v(:,order); % sort the eigenvectors the same way

data = [1 2 3; 4 5 6; 7 8 9; 10 11 12]; % a new dataset
means = mean(data); % calculate the column means
data = center(data); % subtract the means
transdata = v' * data'; % project into the new eigenspace
reconstituted = (v*transdata + repmat(means,size(data,1),1)')'; % project it back the other way, and add the means back
Advertisement

Written by nodisconnect

January 25, 2011 at 2:27 am

Posted in Octave/Matlab

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.