MATLAB: Iterative For Loop for calculating multiple passes of a moving average

for loopMATLABmoving average

I am trying to smooth a given data set (y) with multiple passes of a moving average. I have the code to simply do one pass (I am aware of the smooth function)however, this is for an assignment and the instructor wants us to create our own smoothing code.
What I would like to do is supply a vector of different spans, and have the moving average act on the previous moving average. This way I will be able to find a span set that best smoothes the data.
% Creates a moving average with a defined set of spans.
span = [9,11,21];
y_smooth = y;
for i = 1:length(span)
d = [(span(i)-1)/2];
y_smooth = conv(y_smooth,ones(1,d)/d,'same');
end
%
Does this appear to work?

Best Answer

You want an array of all 1's divided by the number of 1's in the span so that the product and sum will sum to the same average value as the original y. And I will interpret "the span" to mean the whole window width, not half the width like you're doing. So I'd do
kernel = ones(1, spans(k)) / spans(k)
y_smooth = conv(y, kernel, 'same');
Here's a full demo:
% Create sample data:
numPoints = 100;
x = 1 : numPoints;
y = cos(2*pi*x/50) + 0.85*rand(1, numPoints); % Sample data.
% Plot original noisy data
plot(x, y, '-', 'LineWidth', 2);
hold on;
legends{1} = 'Original';
% Creates a moving average with a defined set of spans.
spans = [9, 11, 21];
for k = 1:length(spans)
kernel = ones(1, spans(k)) / spans(k)
y_smooth = conv(y, kernel, 'same');
plot(x, y_smooth, '-', 'LineWidth', 2);
legends{k+1} = sprintf('Span = %d', spans(k));
end
grid on;
legend(legends);