Sum five elements before a specific number

K
Kathryn · Jan 25, 2021 · 1.9K views
Question
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?
Expert Answer
Profile picture of John Williams
John Williams PhD Expert
Answered Aug 14, 2026
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.

Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!