MATLAB: Sum five elements before a specific number

averageaverage five elements before the numberfind peaksSignal Processing Toolbox

Hi, I used "findpeaks" to find the IDs of all the peaks in my data. I need for each peak to find the average of five elements before it. the problem is that some of the peaks don't have five elements before it (say the second value is a peak, therefore, there is only one value before it). How can I tell matlab to average whatever is available but not more than 5 elements?

Best Answer

data_before = Yourdata(max(1, idx-5) : idx-1)
Note that in the case that idx is 1, this will give the empty result, as "empty" is all of the data that is available before the location.