function [v,len] = unitlengthfast(v,dim) <v> is a vector (row or column) or a 2D matrix <dim> (optional) is dimension along which vectors are oriented. if not supplied, assume that <v> is a row or column vector. unit-length normalize <v>. aside from input flexibility, the difference between this function and unitlength.m is that we do not deal with NaNs (i.e. we assume <v> does not have NaNs), and if a vector has 0 length, it becomes all NaNs. we also return <len> which is the original vector length of <v>. when <dim> is not supplied, <len> is a scalar. when <dim> is supplied, <len> is the same dimensions as <v> except collapsed along <dim>. note some weird cases: unitlengthfast([]) is []. unitlengthfast([0 0]) is [NaN NaN]. example: a = [3 0]; isequalwithequalnans(unitlengthfast(a),[1 0])
0001 function [v,len] = unitlengthfast(v,dim) 0002 0003 % function [v,len] = unitlengthfast(v,dim) 0004 % 0005 % <v> is a vector (row or column) or a 2D matrix 0006 % <dim> (optional) is dimension along which vectors are oriented. 0007 % if not supplied, assume that <v> is a row or column vector. 0008 % 0009 % unit-length normalize <v>. aside from input flexibility, 0010 % the difference between this function and unitlength.m is that 0011 % we do not deal with NaNs (i.e. we assume <v> does not have NaNs), 0012 % and if a vector has 0 length, it becomes all NaNs. 0013 % 0014 % we also return <len> which is the original vector length of <v>. 0015 % when <dim> is not supplied, <len> is a scalar. when <dim> is 0016 % supplied, <len> is the same dimensions as <v> except collapsed 0017 % along <dim>. 0018 % 0019 % note some weird cases: 0020 % unitlengthfast([]) is []. 0021 % unitlengthfast([0 0]) is [NaN NaN]. 0022 % 0023 % example: 0024 % a = [3 0]; 0025 % isequalwithequalnans(unitlengthfast(a),[1 0]) 0026 0027 if nargin==1 0028 len = sqrt(v(:).'*v(:)); 0029 v = v / len; 0030 else 0031 if dim==1 0032 len = sqrt(sum(v.^2,1)); 0033 v = v ./ repmat(len,[size(v,1) 1]); % like this for speed. maybe use the indexing trick to speed up even more?? 0034 else 0035 len = sqrt(sum(v.^2,2)); 0036 v = v ./ repmat(len,[1 size(v,2)]); 0037 end 0038 end