vector_unit - computes the unit vector of a 3D Cartesian vector vUnit = vector_unit(v,[origin]) v - an Mx3 vector with M rows of (x,y,z) components origin - the coordinate system origin, a 1x3 vector. This argument is optional, the default is (0,0,0) vUnit - Mx3 matrix of unit vectors for each row in v, ie: vUnit = v ./ [ sqrt( (x-xo).^2 + (y-yo).^2 + (z-zo).^2 ) ];
0001 function vUnit = vector_unit(v,origin) 0002 0003 % vector_unit - computes the unit vector of a 3D Cartesian vector 0004 % 0005 % vUnit = vector_unit(v,[origin]) 0006 % 0007 % v - an Mx3 vector with M rows of (x,y,z) components 0008 % 0009 % origin - the coordinate system origin, a 1x3 vector. 0010 % This argument is optional, the default is (0,0,0) 0011 % 0012 % vUnit - Mx3 matrix of unit vectors for each row in v, ie: 0013 % 0014 % vUnit = v ./ [ sqrt( (x-xo).^2 + (y-yo).^2 + (z-zo).^2 ) ]; 0015 % 0016 0017 % $Revision: 1.2 $ $Date: 2005/01/21 06:21:40 $ 0018 0019 % Licence: GNU GPL, no express or implied warranties 0020 % History: 12/2003, Darren.Weber_at_radiology.ucsf.edu 0021 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 0022 0023 if ~exist('origin','var'), origin = [ 0, 0, 0 ]; end 0024 if isempty(origin), origin = [ 0, 0, 0 ]; end 0025 0026 if ~exist('v','var'), error('no input 3D Cartesian vector'); end 0027 if isempty(v), error('empty input 3D Cartesian vector'); end 0028 0029 Vx = v(:,1) - origin(1); 0030 Vy = v(:,2) - origin(2); 0031 Vz = v(:,3) - origin(3); 0032 0033 distance = sqrt( Vx.^2 + Vy.^2 + Vz.^2 ); 0034 %distance = repmat(distance,1,3); 0035 0036 vUnit = v ./ distance; 0037 0038 return