Calculate running average with NaN
11 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Guillaume
on 3 Aug 2016
If using 2016a or later, simply:
RA = movmean(A, 5, 'omitnan', 'EndPoints', 'discard');
Image Analyst
on 3 Aug 2016
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 Comments
Image Analyst
on 4 Aug 2016
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.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!