MATLAB: Moving average without using movmean() or conv()

moving average

Write a function that performs the moving average of any 1-dimensional input data for any non-zero and positive order M. Make sure to add M-1 zeros at the beginning of the data so that your output data will be the same length as your input data. You must not use built in functions like movmean() or conv().
y[n] = 1/M Σx[n − k]
lower limit k= 0 upper limit M −1
I have this so far:
function
t1=0:0.001:1;t2=1.001:0.001:2;t3=2.001:0.001:3;
t=[t1 t2 t3];
x1=10*ones(1,length(t1));
x2=15*ones(1,length(t2));
x3=20*ones(1,length(t3));
x=[x1 x2 x3];
M=20;
for i=1:length(t)-M
y1(i)=(1/M)*sum(i:i+M-1);
end
y=[zeros(1,M) y1];
figure
subplot(211)
plot(t,x,'b')
ylabel('Signal')
axis([0 3 0 30])
subplot(212)
plot(t,y,'r')
ylabel('Moving avg')
xlabel('Time (s)')
axis([0 3 0 inf])

Best Answer

I'm attaching a fully manual 2-D convolution. It should be easy for you to adapt it to 1-D
Related Question