nanreplace.m 922 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. function m = nanreplace(m,val,mode)
  2. % function m = nanreplace(m,val,mode)
  3. %
  4. % <m> is a matrix
  5. % <val> (optional) is a scalar. default: 0.
  6. % <mode> (optional) is
  7. % 0 means replace all NaNs in <m> with <val>.
  8. % 1 means if the first element of <m> is not finite (i.e. NaN, -Inf, Inf), fill entire matrix with <val>.
  9. % 2 means if it is not true that all elements of <m> are finite and real, fill entire matrix with <val>.
  10. % 3 means replace any non-finite value in <m> in <val>.
  11. % default: 0.
  12. %
  13. % example:
  14. % isequal(nanreplace([1 NaN],0),[1 0])
  15. % isequal(nanreplace([NaN 2 3],0,1),[0 0 0])
  16. % input
  17. if ~exist('val','var') || isempty(val)
  18. val = 0;
  19. end
  20. if ~exist('mode','var') || isempty(mode)
  21. mode = 0;
  22. end
  23. % do it
  24. switch mode
  25. case 0
  26. m(isnan(m)) = val;
  27. case 1
  28. if ~isfinite(m(1))
  29. m(:) = val;
  30. end
  31. case 2
  32. if ~all(isreal(m(:)) & isfinite(m(:)))
  33. m(:) = val;
  34. end
  35. case 3
  36. m(~isfinite(m)) = val;
  37. end