midpoint smoothing spline Suppose we have a time series which have peaks and troughs.(The red curve below)

I would like to get an algorithm which is able to identify the peaks and troughs locations, then find the midpoint between every peak and trough in both X,Y coordinates (the orange points below)

Then connect those midpoints by spline. (the blue line below)

How can I accomplish it using matlab or so? or there is a common solution for such problem?

Thanks in advance,
This is not in matlab but in R.  It seems to do what you need.  The plot below mimics your original in colors (red is the original; circles are peaks and troughs; orange are the interpolating points; and blue is the interpolating signal).





R Code Below

#31438

#install.packages("quantmod")
require(signal)
require(quantmod)
T &lt;- 100
filt &lt;- butter(5,0.1)
red_line &lt;- filter(filt, rnorm(T, 0, 1))    
peaks &lt;- findPeaks(red_line)
valleys &lt;- findValleys(red_line)

plot(as.numeric(red_line), col="red", type="l")
points(peaks + 1, red_line[peaks], col="red")
points(valleys + 1, red_line[valleys], col="red", lwd = 3)

peak_idx &lt;- 1
valley_idx &lt;- 1
counter &lt;- 1

values &lt;- array(0, c(2,T))

while ( (peak_idx &lt;= length(peaks)) &amp;&amp; (valley_idx &lt;= length(valleys)))
{
  mid_idx &lt;- floor((peaks[peak_idx] + valleys[valley_idx]) / 2 )
  mid_value &lt;- (red_line[peaks[peak_idx]] + red_line[valleys[valley_idx]])/2
  points(mid_idx, mid_value, col="orange", lwd = 5)

  values[1,counter] &lt;- mid_idx
  values[2,counter] &lt;- mid_value
  counter &lt;- counter + 1

  if (valleys[valley_idx] &gt; peaks[peak_idx])
  {
    peak_idx &lt;- peak_idx + 1
  }
  else
  {
    valley_idx &lt;- valley_idx + 1
  }
}

values[1,counter] &lt;- T
values[2,counter] &lt;- red_line[T]

interpolated &lt;- spline(values[1,], values[2,], n=T)
lines(interpolated, col="blue")