Calculate running average with NaN

9 次查看(过去 30 天)
Hello,
I have an array similar to array A below, but much larger:
A = [1:15;12 15 20 21 12 14 12 23 41 21 12 11 33 21 42;5 NaN NaN 42 32 42 33 22 12 NaN NaN NaN 12 42 11]';
I would like to calculate the running average of the 3rd column with a window of 4 data points and plot it overlaying on top of the original data. However, I couldnt get it to calculate the correct running average.
RA = [];
for j = 1:(length(A)-4)
RA(j,1) = mean(A(j:j+4,1));
end
figure
plot(A(:,1),A(:,2));
hold on
plot(A(:,1),A(:,3));
plot(A(:,1),RA);
How can I find the RA and overlay it on top of the old data correctly?
Thanks, Max

回答(2 个)

Guillaume
Guillaume 2016-8-3
If using 2016a or later, simply:
RA = movmean(A, 5, 'omitnan', 'EndPoints', 'discard');

Image Analyst
Image Analyst 2016-8-3
Try this:
A = [1:15;12 15 20 21 12 14 12 23 41 21 12 11 33 21 42;5 NaN NaN 42 32 42 33 22 12 NaN NaN NaN 12 42 11]'
% Extract column 3 only.
col3 = A(:, 3)
% Find out where the nans are.
nanIndexes = isnan(col3)
% Turn nans into zeros
col3(nanIndexes) = 0
kernel = [1,1,1,1]; % Kernel to look at 4 elements.
% Do a running sum.
sums = conv(col3, kernel, 'valid')
% Do a running count. Count how many non-nans there are. In other words, how many good numbers.
counts = conv(double(~nanIndexes), kernel, 'valid')
% Divide them to get the means.
runningMeans = sums ./ counts
runningMeans =
23.5
37
38.6666666666667
37.25
32.25
27.25
22.3333333333333
17
12
12
27
21.6666666666667
  2 个评论
Max Bernstein
Max Bernstein 2016-8-4
I had to change the 'valid' to 'same' in order to get the same array size to plot. However, this method seems to shift the magnitude of the running average down for some reason.
Image Analyst
Image Analyst 2016-8-4
With a window size of 4, there are 1 or 2 elements outside when the 'same' option is used. Normally the window size is odd anyway. But when the window is at the far left, about half the window will overlap the array and half will be "off" the far left end of the array. Same for the right side. You have to decide how you want to handle what's called "edge effects" which is what happens when the moving window starts to move off the main array.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by