How to avoid the ending drop of the moving average curve? I'm playing around with the built-in matlab movmean function which, using default options, creates the simple and centered moving average of given data (I'm pretty sure there is a built-in function in other programming languages too).
I noticed that in some cases the curve badly fits/smoothens the data at the last values, consider the following example
data = [386 379 295 238 159 190 384 402 552 347 463 259 412 481 523 589 611 479 320 403 642];
plot(movmean(data,7)) % 7 since data are collected daily and show cycles of length 7
hold on
plot(data)
legend('movmean','data','Location','northwest')

Since data are increasing, the movmean is supposed to increase too, while it drops at the end (look at the image below).
Is there a way to avoid this behaviour?
p.s. if you don't have the movmean function you can use this
S = [];
for c = 1:numel(data)
    f = [c-3:c-1 c c+1:c+3]; % centered with 3 values on left and 3 on right
    f = f(f>0 & f<=numel(data));
    S(c) = sum(data(f))/numel(f);
end


 A: It's inherent in the nature of using a centred moving average; the window is truncated to what is available. You're seeing the same behaviour at the start. With the exception of the last point, all your last few points are quite a bit lower than the average, so you see a dip. Your options are to change the size of the window, discard the last few points of the moving average (because they can't be calculated in the same way as other points), or use a different type of smoothing function.
Alternately you could create some extra data points, say by duplicating the last point a few times, but the average won't reflect the true value then
A: One method is to extrapolate the trend using a regression of the last n-points of the moving average line before you start incorporating the points outside of your series.
Typically if you have some seasonal pattern then n-points is set to the period size so if you have daily data for 10 years then it would be set to the last 365 points (1 period).
For yours, sounds like you have a cycle of 7 so do the last 7 points of the moving average line for the regression and use those points when you run out of real estate on the right of your center.
A: A naive yet simple way is to compute a convex combination of data and moving average, using a small coefficient 0<i<0.5 for the data and i-1 for the moving average.
data = [386 379 295 238 159 190 384 402 552 347 463 259 412 481 523 589 611 479 320 403 642];
for i = .1:.01:.4
  plot(movmean(data,7))
  hold on
  plot(data)
  plot(data*i+movmean(data,7)*(1-i))
  legend('movmean','data',"data*"+i+"+movmean*"+(1-i),'Location','northwest')
  pause(.1)
  clf
end


