% An example for the PCA computation % % created by darko zikic (zikic@in.tum.de) % 2006-11-23 % for Lecture Basic Mathematical Tools for Imaging and Visualization % at Chair for Computer Aided Medical Procedures & Augmented Reality % Department for Computer Science, Technische Universität München % Winter Term 2006 % settings ---------------------------------------------------------------- % number of used points n = 300; % size of plots XMIN = -2 ; XMAX = 2 ; YMIN = -2 ; YMAX = 2 ; % create data ------------------------------------------------------------- disp(' - Create Data'); pause p = zeros(2,n); p(1,:) = 0.1*(randn(1,n)-0.5) + [0:1/(n-1):1] ;%+ 10*randn(1,n); p(2,:) = 0.01*(randn(1,n)-0.5) + 0.6*[0:1/(n-1):1] ;%[1:n]*0.5 + 10*randn(1,n); figure, plot(p(1,:),p(2,:),'+'); title('data'); axis; hold on, plot([0 1 ; 0 0 ; 0 -1 ; 0 0]',[0 0; 0 1; 0 0; 0 -1]','g'); axis([XMIN XMAX YMIN YMAX]); axis equal % subtract the mean ------------------------------------------------------- disp(' - Subtract the mean from Data'); pause p(1,:) = p(1,:) - mean(p(1,:)); p(2,:) = p(2,:) - mean(p(2,:)); figure, plot(p(1,:),p(2,:),'+'); title('data - mean'); axis; hold on, plot([0 1 ; 0 0 ; 0 -1 ; 0 0]',[0 0; 0 1; 0 0; 0 -1]','g'); axis([XMIN XMAX YMIN YMAX]); axis equal % compute covariance ------------------------------------------------------ disp(' - Compute Covariance'); pause C = cov(p') % compute eigenvectors and eigenvalues of C ------------------------------- disp(' - Compute eigenvectors and eigenvalues of C'); pause [V,D] = eig(C) % display eigenvectors ---------------------------------------------------- disp(' - Display Eigenvectors'); pause figure, plot(p(1,:),p(2,:),'+'); title('shifted data with eigenvectors'); axis; hold on, plot([0 V(1,1) ; 0 V(1,2) ; 0 -V(1,1) ; 0 -V(1,2)]',[0 V(2,1); 0 V(2,2); 0 -V(2,1); 0 -V(2,2)]','r'); axis([XMIN XMAX YMIN YMAX]); axis equal % display eigenvectors scaled by eigenvalues ------------------------------ disp(' - Display eigenvectors scaled by eigenvalues'); pause % scale vectors by values Vs = V*D; Vs = Vs / max2((Vs.*Vs).^0.5); % scale larger for display % display eigenvectors scaled by eigenvalues figure, plot(p(1,:),p(2,:),'+'); title('shifted data with eigenvectors scaled by eigenvalues'); axis; hold on, plot([0 Vs(1,1) ; 0 Vs(1,2) ; 0 -Vs(1,1) ; 0 -Vs(1,2)]',[0 Vs(2,1); 0 Vs(2,2); 0 -Vs(2,1); 0 -Vs(2,2)]','r'); axis([XMIN XMAX YMIN YMAX]); axis equal % transform to standard coordinate system --------------------------------- disp(' - Compute Feature Matrix- reorder eigenvectors'); pause % set up feature matrix F = V; if (D(1,1)