Search code examples
matlabfilteringsignal-processingmedian

Median of arbitrary datapoint around index - MATLAB


I've been using the findpeaks function with great success to detect peaks in my signal. My next step is to clean these identified peaks, for which I have the indices.

My goal is to calculate the median of Y data points before and Y data points after a given index and replace whatever values (noise) there are with these new values (the calculated median).

Something like this:

%  points before, peak, points after
%        ↓         ↓         ↓
x = [1, 2, 3, 1,   34,   3, 2, 1, 3]

Calculate the median of the 4 data points preceding and following my peak the peak of 34...

Median of [1,2,3,1,3,2,1,3] is 2.

Replace my peak with this new value:

% Replaced peak with surrounding median
%                  ↓
x1 = [1, 2, 3, 1,  2,  3, 2, 1, 3]

Any suggestion on how to implement this?


Solution

  • Find the peaks and replace them with the results of medfilt1()

    [~,idx]=findpeaks(x);
    if ~isempty(idx)
        m = medfilt1(x,9);
        x(idx) = m(idx);
    end