vectorlength.m 932 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. function f = vectorlength(m,dim)
  2. % function f = vectorlength(m,dim)
  3. %
  4. % <m> is a matrix
  5. % <dim> (optional) is the dimension of interest.
  6. % if supplied, calculate vector length of each case oriented along <dim>.
  7. % if [] or not supplied, calculate vector length of entire matrix
  8. %
  9. % calculate vector length of <m>, either of individual cases (in which case
  10. % the output is the same as <m> except collapsed along <dim>) or globally
  11. % (in which case the output is a scalar).
  12. %
  13. % we ignore NaNs gracefully.
  14. %
  15. % note some weird cases:
  16. % vectorlength([]) is [].
  17. % vectorlength([NaN NaN]) is 0
  18. %
  19. % example:
  20. % a = [1 1];
  21. % isequal(vectorlength(a),sqrt(2))
  22. % a = [1 NaN; NaN NaN];
  23. % isequal(vectorlength(a,1),[1 0])
  24. % deal with NaNs
  25. m(isnan(m)) = 0;
  26. % handle weird case up front
  27. if isempty(m)
  28. f = [];
  29. return;
  30. end
  31. % do it
  32. if ~exist('dim','var') || isempty(dim)
  33. f = sqrt(dot(m(:),m(:),1));
  34. else
  35. f = sqrt(dot(m,m,dim));
  36. end