Understand the fillmissing function with movmean

Hi, I would like to ask how the fillmissing movmean method works.
I got A
A = [1 2 5;4 5 7;NaN -1 8;7 6 0];
A1 = fillmissing(A,'movmean',2);
A2 = fillmissing(A,'movmean',3);
A1 turns the NaN into 4, and A2 turns into 5.5.
I tried to open the function fillmissing but wasn't able to find how the calculation is made.
The 4 is the result of a nanmean of (4+NaN)/1 = 4, divided by 1 because it is a nanmean? The 5 is the result of a nanmean of (4+NaN+7)/2 = 11/3 = 5.5? divided by 2 because it is a nanmean?

 Accepted Answer

The missing elements are in effect calculated with
movmean(A, k, 'omitnan')
with k your windows size.
As per the movmean documentation, when 'omitnan' is specified, the window is reduced as necessary when NaNs are encountered. When k is 2 movmean is normally the mean of the element and the previous one, so when a NaN is encountered the result is just the previous element, hence why you get 4. When k is 3 the |movmean |is the mean of the element and the ones on either side, so when a NaN is encountered the result is just the mean of the neighbouring elements.
edit: the best way to actually understand what is going on is to set a breakpoint at the start of the fillmissing function and step through it after you've called it.

5 Comments

Thanks, if you don't mind I got another question, since my original data has a lot of consecutive NaN's, an example:

A = [1 2 NaN;4 5 7;NaN -1 8;NaN 6 0; 5 NaN 9; 11 4 NaN];

In the 1st column and row 3 and 4 I have 2 consecutive NaN's,

For a movmean with a k = 3:

For the Nan in row 3, i get that it turns out the number 4, but in the row 4, since the row 3 was already inputed, why the outcome is 5 and not 4.5? Why he doesnt update the previous NaN to the number 4?

since the row 3 was already inputed. movmean does not take that into account, it only looks at the original values. For row 4, it is [Nan; Nan; 5], so this reduces to mean([5]) == 5.

I See, is there any function already done that do what i sugest? he does the substitution of the 1st NaN for the movmean, and in the 2nd NaN, the value of the 1st NaN is not a NaN but the value previously calculated?, and so on

There is no fillmissing option to do what you want, and it's a bit unusual to want that.

To me, it looks like you would be better off with an interpolation rather than a moving mean. Wouldn't

fillmissing(A, 'linear')

be good enough for you?

perhaps, i was just thinking on every options possible.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 27 Mar 2018

Commented:

on 28 Mar 2018

Community Treasure Hunt

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

Start Hunting!