46 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Matlab
		
	
	
	
	
	
			
		
		
	
	
			46 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Matlab
		
	
	
	
	
	
function covareigen3( x, y, z )
 | 
						|
% computes covariance matrix from the triples x, y, z
 | 
						|
% diagonalizes covariance matrix
 | 
						|
% x, y and z are column vectors
 | 
						|
 | 
						|
    % covariance matrix:
 | 
						|
    cv = cov( [ x y z ] );
 | 
						|
 | 
						|
    % eigen values:
 | 
						|
    [ v , d] = eig( cv )
 | 
						|
 | 
						|
    % plots:
 | 
						|
    subplot( 1, 2, 1 );
 | 
						|
    hold on;
 | 
						|
 | 
						|
    % scatter plot:
 | 
						|
    view( 3 );
 | 
						|
    scatter3( x, y, z, 0.1, 'b', 'filled', 'MarkerEdgeColor', 'blue' );
 | 
						|
    xlabel( 'x' );
 | 
						|
    ylabel( 'y' );
 | 
						|
    zlabel( 'z' );
 | 
						|
    grid on;
 | 
						|
 | 
						|
    % plot eigenvectors:
 | 
						|
    quiver3( ones( 1, 3 ).*mean( x ), ones( 1, 3 )*mean(y), ones( 1, 3 )*mean(z), v(1,:).*sqrt(diag(d))', v(2,:).*sqrt(diag(d))', v(3,:).*sqrt(diag(d))', 'r', 'LineWidth', 3, 'AutoScale', 'off', 'AutoScaleFactor', 1.0, 'MaxHeadSize', 0.7 )
 | 
						|
    
 | 
						|
    %axis( 'equal' );
 | 
						|
    hold off;
 | 
						|
 | 
						|
    % sort the eigenvalues:
 | 
						|
    [d,inx] = sort( diag(d), 'descend' );
 | 
						|
    
 | 
						|
    subplot( 2, 2, 2 );
 | 
						|
    hold on;
 | 
						|
    % subtract means:
 | 
						|
    x = x - mean( x );
 | 
						|
    y = y - mean( y );
 | 
						|
    % project onto eigenvectors:
 | 
						|
    nx = [ x y z ] * v(:,inx(1));
 | 
						|
    ny = [ x y z ] * v(:,inx(2));
 | 
						|
    scatter( nx, ny, 'b', 'filled', 'MarkerEdgeColor', 'white' );
 | 
						|
    axis( 'equal' );
 | 
						|
    hold off;
 | 
						|
 | 
						|
end
 |