NORMALIZEVECTOR Normalize a vector to have norm equal to 1. V2 = normalizeVector(V); Returns the normalization of vector V, such that ||V|| = 1. V can be either a row or a column vector. When V is a M-by-N array, normalization is performed for each row of the array. When V is a M-by-N-by-2 array, normalization is performed along the last dimension of the array. Example: vn = normalizeVector([3 4]) vn = 0.6000 0.8000 vectorNorm(vn) ans = 1 See Also: vectors2d, vectorNorm
0001 function vn = normalizeVector(v) 0002 %NORMALIZEVECTOR Normalize a vector to have norm equal to 1. 0003 % 0004 % V2 = normalizeVector(V); 0005 % Returns the normalization of vector V, such that ||V|| = 1. V can be 0006 % either a row or a column vector. 0007 % 0008 % When V is a M-by-N array, normalization is performed for each row of 0009 % the array. 0010 % 0011 % When V is a M-by-N-by-2 array, normalization is performed along the 0012 % last dimension of the array. 0013 % 0014 % Example: 0015 % vn = normalizeVector([3 4]) 0016 % vn = 0017 % 0.6000 0.8000 0018 % vectorNorm(vn) 0019 % ans = 0020 % 1 0021 % 0022 % See Also: 0023 % vectors2d, vectorNorm 0024 % 0025 0026 % --------- 0027 % author : David Legland 0028 % INRA - TPV URPOI - BIA IMASTE 0029 % created the 29/11/2004. 0030 % 0031 0032 % HISTORY 0033 % 2005-01-14 correct bug 0034 % 2009-05-22 rename as normalizeVector 0035 % 2011-01-20 use bsxfun 0036 0037 if ismatrix(v) 0038 vn = bsxfun(@rdivide, v, sqrt(sum(v.^2, 2))); 0039 else 0040 vn = bsxfun(@rdivide, v, sqrt(sum(v.^2, ndims(v)))); 0041 end