% FUNCTION Y = RUNNING_MEDIAN(X, MEDIAN_WIN)
%
% X: vector of data
% MEDIAN_WIN: odd integer
%
% Y: vector of same size as X
%
% by Guillaume LATHOUD at IDIAP (lathoud@idiap.ch)

function y = running_median(x, median_win)

if mod(median_win, 2) < 1
  error('running_median needs an odd window size');
end

if median_win < 2
  y = x;
  return;
end

half_win = floor((median_win-1) / 2);

% Mirror signal at borders
aux = x(:);
aux = [aux((1+half_win):-1:2); aux; aux((end-1):-1:(end-half_win))];

% shift it in both directions
for a = 1:half_win
  zz = zeros(a,1);
  aux(:,end+1) = [aux((1+a):end, 1); zz];
  aux(:,end+1) = [zz; aux(1:(end-a), 1)];
end

% Median
y = nanmedian(aux .') .';

% Remove mirrored samples
y = y((1+half_win):(end-half_win));
if size(x,2) > 1
  y = y';
end
