www.gusucode.com > Eigenvalues_eigenvectors源码程序 > Eigenvalues_eigenvectors/code/Demo.m
%% Eigenvalues/eigenvectors % Alireza Asvadi % http://www.a-asvadi.ir % 2012 % Questions regarding the code may be directed to alireza.asvadi@gmail.com %% Clear Memory & Command Window clc clear all close all %% Points X = [0 -1;-1 0;2 3;3 2]; % set of point vectors M = mean(X); % mean vector represents the center of the points C = cov(X); % covariance matrix describes how dispersedly the points are distributed %% Show (The original four points) x1 = 4; x2 = 4; % x1 - x2 plane size to show disp('X'); disp(X) disp('M'); disp(M) disp('C'); disp(C) figure() plot([X(:,1);X(1,1)],[X(:,2);X(1,2)],'g','LineWidth',2) % shows that the eigenvectors of the covariance matrix hold on % for a set of point vectors represents the principal axes of plot(X(:,1),X(:,2),'*r','LineWidth',4) % the distribution and its eigenvaluesare related with plot(M(1),M(2),'*k','LineWidth',2) % the lengths of the distribution along the principal axes. axis([-x1 x1 -x2 x2]) % The difference among the eigenvalues determines how grid on % oblong the overall shape of the distribution is. xlabel('dimension 1') ylabel('dimension 2') title('Eigenvalues/eigenvectors of a covariance matrix') %% Eigens & Transform [V,D] = eig(C); % Eigenvalues and eigenvectors (V is in the from of modal matrix, eigenvalues are on the main diagonal of D) Y = (X - repmat(M,size(X,1),1))*V; % Transform the four point vectors by using the modal matrix %% Show (the new points corresponding to the original four points) disp('V'); disp(V) disp('D'); disp(D) disp('Y'); disp(Y) plot([Y(:,1);Y(1,1)],[Y(:,2);Y(1,2)],'g','LineWidth',2) Mp = mean(Y); plot(Y(:,1),Y(:,2),'*r','LineWidth',4) plot(Mp(1),Mp(2),'*k','LineWidth',2) hold off %% Bonus!: Kernel % Q = 0.1; % [x,y] = meshgrid(-x1:Q:x1,-x2:Q:x2); % P = [x(:),y(:)]; % Z = zeros(size(P,1),1); % for i = 1:size(P,1) % Z(i,1) = exp( (-1/2) * (P(i,:)-M) * inv(C) * (P(i,:)-M)' ); % end % z = reshape(Z,[(2*x1)/Q+1 (2*x2)/Q+1]); % %% Show Kernel % figure() % plot3(X(:,1),X(:,2),zeros(size(X,1)),'*r','LineWidth',4) % hold on % surf(y,x,z) % try mesh(hidden off) surfc surfl % colormap hsv % try hsv bone hot cool summer autumn winter gray copper pink Lines % alpha(.4) % hold off % axis([-x1 x1 -x2 x2 0 1]) % grid on % xlabel('dimension 1') % ylabel('dimension 2')