MATLAB: How to take an average around unusual values

averagingfinding valuesindexinglogical indexMATLAB

Hi,
I have a matrix with two rows – one that has values of interest and then the other that has corresponding moving standard deviation values. Sometimes there are spikes in the second array (std gets too high) – and there could be several of them. I already know how to identify these spikes – they are 3 standard deviation away from the mean (of moving standard deviation values).
My problem is to remove these spikes once they are identified, by averaging the values in the first row: take a value right before the spike occurred, add the value right after the spike ended (std values are back to being less than 3 standard dev. from the mean), and then divide those by two – and fill the elements corresponding to the spike with those averages.
Could anyone please help? I'm confused with how the indexing would work in this case, since there could be multiple occurrences of an event, and the averages should be taken for each of those events, properly.
Thanks!!

Best Answer

With interp1:
signal = rand(1000, 1); % Test data, the first column of your matrix
isSpike = rand(1000, 1) < 0.01;
signal(isSpike) = interp1(signal(~isSpike), find(~isSpike), find(isSpike));
Related Question