VECTORNORM Compute norm of a vector, or of a set of vectors. N = vectorNorm(V); Returns the euclidean norm of vector V. N = vectorNorm(V, N); Specifies the norm to use. N can be any value greater than 0. N=1 -> city lock norm N=2 -> euclidean norm N=inf -> compute max coord. When V is a MxN array, compute norm for each vector of the array. Vector are given as rows. Result is then a [M*1] array. Example n1 = vectorNorm([3 4]) n1 = 5 n2 = vectorNorm([1, 10], inf) n2 = 10 See also vectors2d, vectorAngle
0001 function n = vectorNorm(v, varargin) 0002 %VECTORNORM Compute norm of a vector, or of a set of vectors. 0003 % 0004 % N = vectorNorm(V); 0005 % Returns the euclidean norm of vector V. 0006 % 0007 % N = vectorNorm(V, N); 0008 % Specifies the norm to use. N can be any value greater than 0. 0009 % N=1 -> city lock norm 0010 % N=2 -> euclidean norm 0011 % N=inf -> compute max coord. 0012 % 0013 % When V is a MxN array, compute norm for each vector of the array. 0014 % Vector are given as rows. Result is then a [M*1] array. 0015 % 0016 % Example 0017 % n1 = vectorNorm([3 4]) 0018 % n1 = 0019 % 5 0020 % 0021 % n2 = vectorNorm([1, 10], inf) 0022 % n2 = 0023 % 10 0024 % 0025 % See also 0026 % vectors2d, vectorAngle 0027 % 0028 0029 % ------ 0030 % Author: David Legland 0031 % E-mail: david.legland@inrae.fr 0032 % Created: 2005-02-21 0033 % Copyright 2005-2024 INRA - TPV URPOI - BIA IMASTE 0034 0035 % extract the type of norm to compute 0036 d = 2; 0037 if ~isempty(varargin) 0038 d = varargin{1}; 0039 end 0040 0041 if d==2 0042 % euclidean norm: sum of squared coordinates, and take square root 0043 n = sqrt(sum(v.*v, ndims(v))); 0044 0045 elseif d==1 0046 % absolute norm: sum of absolute coordinates 0047 n = sum(abs(v), ndims(v)); 0048 0049 elseif d==inf 0050 % infinite norm: uses the maximal corodinate 0051 n = max(v, [], ndims(v)); 0052 0053 else 0054 % Other norms, use explicit but slower expression 0055 n = power(sum(power(v, d), ndims(v)), 1/d); 0056 0057 end