spm_detrend.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function y = spm_detrend(x,p)
  2. % Polynomial detrending over columns
  3. % FORMAT y = spm_detrend(x,p)
  4. % x - data matrix
  5. % p - order of polynomial [default: 0]
  6. %
  7. % y - detrended data matrix
  8. %__________________________________________________________________________
  9. %
  10. % spm_detrend removes linear and nonlinear trends from column-wise data
  11. % matrices.
  12. %__________________________________________________________________________
  13. % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
  14. % Karl Friston
  15. % $Id: spm_detrend.m 7271 2018-03-04 13:11:54Z karl $
  16. % Check for cell arrays
  17. %-------------------------------------------------------------------------
  18. if iscell(x)
  19. if nargin == 1
  20. p = 0;
  21. end
  22. y = x;
  23. for i = 1:numel(x)
  24. y{i} = spm_detrend(x{i},p);
  25. end
  26. return
  27. end
  28. % defaults
  29. %--------------------------------------------------------------------------
  30. [m,n] = size(x);
  31. if ~m || ~n
  32. y = [];
  33. return
  34. end
  35. if nargin == 1
  36. p = 0;
  37. end
  38. % centre columns
  39. %--------------------------------------------------------------------------
  40. if ~p
  41. y = x - ones(m,1)*mean(x);
  42. return
  43. end
  44. % polynomial adjustment
  45. %--------------------------------------------------------------------------
  46. G = zeros(m,p + 1);
  47. for i = 0:p
  48. d = (1:m).^i;
  49. G(:,i+1) = d(:);
  50. end
  51. y = x - G*(pinv(full(G))*x);