![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/176698/image.png)
Iterative For Loop for calculating multiple passes of a moving average?
3 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Image Analyst
on 16 Jan 2017
Edited: Image Analyst
on 6 Sep 2018
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);
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/176698/image.png)
3 Comments
Shelby Jacobs
on 6 Sep 2018
How could this code be edited to combine spans so that the data would pass through all indicated spans before plotting?
Image Analyst
on 6 Sep 2018
I have no idea what that means. What does "pass through" mean exactly? And what are the "Indicated" spans?
More Answers (1)
Jyotish Robin
on 16 Jan 2017
Hi Jacob,
Span parameter usually refers to the number of terms in the moving average, which is the window size If N is the number of neighboring data points on either side of a sample value , then 2N+1 is the span.
If we want to do moving average by convolution having a window size of w, we shall use the following k kernel:
k=[1/w 1/w...1/w 1/w]
Hope it helps!
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!