function y_filt = running_median(y,n)
% SYNTAX:
%                    y_filt = running_median(y,n);
% INUPTS:
%                    y: timeseries to filter (with equal time steps)
%                    n: window size
% OUTPUTS:
%               y_filt: filtered timeseries

row_vector = size(y,2) > size(y,1);
if row_vector
    y = y';
end

% filter
y_mat = nan(n,length(y)+1-n);
for ii = 1:n
    y_mat(ii,:) = y(ii:end-n+ii);
end
y_filt = nanmedian(y_mat);

% Endpoints
leg = (n-1)/2;
for ii = 1:leg
    start_segment(ii) = nanmedian(y(1:ii+leg));
    end_segment(ii) = nanmedian(y(end-2*leg+ii:end));
end

y_filt = [start_segment y_filt end_segment]';

if row_vector
    y_filt = y_filt';
end
