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
댓글 수: 0
답변 (2개)
Guillaume
2016년 8월 3일
If using 2016a or later, simply:
RA = movmean(A, 5, 'omitnan', 'EndPoints', 'discard');
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
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 Center 및 File Exchange에서 NaNs에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!