# Iterative For Loop for calculating multiple passes of a moving average?

21 ビュー (過去 30 日間)
Jacob B 2017 年 1 月 11 日
コメント済み: Image Analyst 2018 年 9 月 6 日
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?

サインインしてコメントする。

### 採用された回答

Image Analyst 2017 年 1 月 16 日

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); ##### 3 件のコメント表示非表示 2 件の古いコメント
Image Analyst 2018 年 9 月 6 日
I have no idea what that means. What does "pass through" mean exactly? And what are the "Indicated" spans?

サインインしてコメントする。

### その他の回答 (1 件)

Jyotish Robin 2017 年 1 月 16 日
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!

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!