Home > GLMdenoise > utilities > vectorlength.m

vectorlength

PURPOSE ^

function f = vectorlength(m,dim)

SYNOPSIS ^

function f = vectorlength(m,dim)

DESCRIPTION ^

 function f = vectorlength(m,dim)

 <m> is a matrix
 <dim> (optional) is the dimension of interest.
   if supplied, calculate vector length of each case oriented along <dim>.
   if [] or not supplied, calculate vector length of entire matrix

 calculate vector length of <m>, either of individual cases (in which case
 the output is the same as <m> except collapsed along <dim>) or globally
 (in which case the output is a scalar).

 we ignore NaNs gracefully.
 
 note some weird cases:
   vectorlength([]) is [].
   vectorlength([NaN NaN]) is 0

 example:
 a = [1 1];
 isequal(vectorlength(a),sqrt(2))
 a = [1 NaN; NaN NaN];
 isequal(vectorlength(a,1),[1 0])

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function f = vectorlength(m,dim)
0002 
0003 % function f = vectorlength(m,dim)
0004 %
0005 % <m> is a matrix
0006 % <dim> (optional) is the dimension of interest.
0007 %   if supplied, calculate vector length of each case oriented along <dim>.
0008 %   if [] or not supplied, calculate vector length of entire matrix
0009 %
0010 % calculate vector length of <m>, either of individual cases (in which case
0011 % the output is the same as <m> except collapsed along <dim>) or globally
0012 % (in which case the output is a scalar).
0013 %
0014 % we ignore NaNs gracefully.
0015 %
0016 % note some weird cases:
0017 %   vectorlength([]) is [].
0018 %   vectorlength([NaN NaN]) is 0
0019 %
0020 % example:
0021 % a = [1 1];
0022 % isequal(vectorlength(a),sqrt(2))
0023 % a = [1 NaN; NaN NaN];
0024 % isequal(vectorlength(a,1),[1 0])
0025 
0026 % deal with NaNs
0027 m(isnan(m)) = 0;
0028 
0029 % handle weird case up front
0030 if isempty(m)
0031   f = [];
0032   return;
0033 end
0034 
0035 % do it
0036 if ~exist('dim','var') || isempty(dim)
0037   f = sqrt(dot(m(:),m(:),1));
0038 else
0039   f = sqrt(dot(m,m,dim));
0040 end

Generated on Fri 01-Aug-2014 12:03:17 by m2html © 2005