问题
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?
回答1:
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
回答2:
I think it is most efficient to process each peak individually. I'll demonstrate in a step-by-step manner in the following.
Take the neighborhood of each peak
x(idx_max-N:idx_max+N)
with N
the number of elements to the left and right of the peak, respectively. The median of the neighborhood around each peak can be computed by using MATLAB's median() function:
median(x(idx_max-N:idx_max+N))
Now, you can replace either only the element at the peak position with the median of the neighborhood:
x(idx_max) = median(x(idx_max-N:idx_max+N))
or easily replace all elements of the neighborhood with the median value:
x(idx_max-N:idx_max+N) = median(x(idx_max-N:idx_max+N))
(Note that scalar expansion is used in the last example to assign a scalar value to multiple elements of an array.)
来源:https://stackoverflow.com/questions/47368216/median-of-arbitrary-datapoint-around-index-matlab