From 2b98bd80f011f583deca0ec855cd170b1e06c037 Mon Sep 17 00:00:00 2001 From: neingeist Date: Wed, 19 Nov 2014 20:47:27 +0100 Subject: [PATCH] Implement PCA --- ex7/pca.m | 60 +++++++++++++++++++++++++++---------------------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/ex7/pca.m b/ex7/pca.m index d13f96f..bda87b5 100644 --- a/ex7/pca.m +++ b/ex7/pca.m @@ -1,31 +1,29 @@ -function [U, S] = pca(X) -%PCA Run principal component analysis on the dataset X -% [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X -% Returns the eigenvectors U, the eigenvalues (on diagonal) in S -% - -% Useful values -[m, n] = size(X); - -% You need to return the following variables correctly. -U = zeros(n); -S = zeros(n); - -% ====================== YOUR CODE HERE ====================== -% Instructions: You should first compute the covariance matrix. Then, you -% should use the "svd" function to compute the eigenvectors -% and eigenvalues of the covariance matrix. -% -% Note: When computing the covariance matrix, remember to divide by m (the -% number of examples). -% - - - - - - - -% ========================================================================= - -end +function [U, S] = pca(X) +%PCA Run principal component analysis on the dataset X +% [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X +% Returns the eigenvectors U, the eigenvalues (on diagonal) in S +% + +% Useful values +[m, n] = size(X); + +% You need to return the following variables correctly. +U = zeros(n); +S = zeros(n); + +% ====================== YOUR CODE HERE ====================== +% Instructions: You should first compute the covariance matrix. Then, you +% should use the "svd" function to compute the eigenvectors +% and eigenvalues of the covariance matrix. +% +% Note: When computing the covariance matrix, remember to divide by m (the +% number of examples). +% + +Sigma = 1/m * X'*X; % covariance matrix + +[U, S, V] = svd(Sigma); + +% ========================================================================= + +end