nanmovmean.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function y = nanmovmean( x, mlag, mspan )
  2. % (C) Demetrio Ferro demetrio.ferro@upf.edu
  3. % Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
  4. % the function applies a sliding nanmean to the first dimension of input x
  5. % centered at each mlag and with width msize, allowing overlap for msize > mlag
  6. % e.g. size(x,1)=12, mlag=2 msize=6
  7. % x : [ 1 2 3 4 5 6 7 8 9 10 11 12 ] [ - - ] [ - - - - - - ]
  8. %
  9. % y(1)=nanmean([ 1 2 3 4 ]);
  10. % y(2)=nanmean([ 1 2 3 4 5 6 ]);
  11. % y(3)=nanmean([ 3 4 5 6 7 8 ]);
  12. % y(4)=nanmean([ 5 6 7 8 9 10 ]);
  13. % y(5)=nanmean([ 7 8 9 10 11 12]);
  14. % y(6)=nanmean([ 9 10 11 12]);
  15. % choose msize and mlag as multiple of 2 or fix this code accordingly
  16. if mod(mlag,2)==1
  17. error('the parameter mlag has to be divisible by 2.')
  18. end
  19. if isscalar(mspan)
  20. if mod(mspan,2)==1
  21. error('the parameter mspan has to be divisible by 2.')
  22. else
  23. mspan_bf=mspan/2;
  24. mspan_af=mspan/2;
  25. end
  26. elseif isvector(mspan) && length(mspan)==2
  27. mspan_bf=mspan(1);
  28. mspan_af=mspan(2);
  29. else
  30. error('specify a valid mspan value');
  31. end
  32. if isvector(x)
  33. L=length(x);
  34. y=nan(1,ceil(L/mlag));
  35. for ll=1:ceil(L/mlag)
  36. ctsmp=max(((ll-1)*mlag)-mspan_bf+1+mlag/2,1) : min(((ll)*mlag)+mspan_af-mlag/2,L);
  37. y(ll)=nanmean(x(ctsmp));
  38. end
  39. elseif ismatrix(x)
  40. [L,M]=size(x);
  41. y=nan(ceil(L/mlag),M);
  42. for ll=1:ceil(L/mlag)
  43. ctsmp=max(((ll-1)*mlag)-mspan_bf+1+mlag/2,1) : min(((ll)*mlag)+mspan_af-mlag/2,L);
  44. y(ll,:)=nanmean(x(ctsmp,:),1);
  45. end
  46. end
  47. end