NORMALIZEVECTOR3D Normalize a 3D vector to have norm equal to 1. V2 = normalizeVector3d(V); Returns the normalization of vector V, such that ||V|| = 1. Vector V is given as a row vector. If V is a N-by-3 array, normalization is performed for each row of the input array. If V is a M-by-N-by-3 array, normalization is performed along the last dimension of the array. See also: vectors3d, vectorNorm3d
0001 function vn = normalizeVector3d(v) 0002 %NORMALIZEVECTOR3D Normalize a 3D vector to have norm equal to 1. 0003 % 0004 % V2 = normalizeVector3d(V); 0005 % Returns the normalization of vector V, such that ||V|| = 1. Vector V is 0006 % given as a row vector. 0007 % 0008 % If V is a N-by-3 array, normalization is performed for each row of the 0009 % input array. 0010 % 0011 % If V is a M-by-N-by-3 array, normalization is performed along the last 0012 % dimension of the array. 0013 % 0014 % See also: 0015 % vectors3d, vectorNorm3d 0016 % 0017 0018 % --------- 0019 % author : David Legland 0020 % INRA - TPV URPOI - BIA IMASTE 0021 % created the 29/11/2004. 0022 % 0023 0024 % HISTORY 0025 % 2005-11-30 correct a bug 0026 % 2009-06-19 rename as normalizeVector3d 0027 % 2010-11-16 use bsxfun (Thanks to Sven Holcombe) 0028 0029 if ismatrix(v) 0030 vn = bsxfun(@rdivide, v, sqrt(sum(v.^2, 2))); 0031 else 0032 vn = bsxfun(@rdivide, v, sqrt(sum(v.^2, ndims(v)))); 0033 end