Fill NaN cells using surrounding data values

Hi,
I would like to fill NaN cells in the rows of a matrix with the mean of the immediately surrounding values.
For example I would like to convert
>> A=magic(5);
>> A(:,2:4)=NaN;
>> A(1:2,:)=NaN;
>> A
A =
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
4 NaN NaN NaN 22
10 NaN NaN NaN 3
11 NaN NaN NaN 9
>>
To this:
>> A
A =
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
4.0000 13.0000 13.0000 13.0000 22.0000
10.0000 6.5000 6.5000 6.5000 3.0000
11.0000 10.0000 10.0000 10.0000 9.0000
>>
Only converting those NaN cells that are surrounded on the row by non-NaN values.
I hope this is clear.
Thanks very much

 Accepted Answer

You may wish to see John's MATLAB File Exchange contribution inpaint_nans

1 Comment

This looks like it might do the trick, I will give it a shot.
Thanks

Sign in to comment.

More Answers (2)

It can't be that hard - did you know there is an "isnan()" function, as well as mean() and sum()? Give it a shot yourself first - it's not hard.
Sure, let me preface this with the comment that I am definitely a beginner MATLAB user.
I can solve the example that I gave above (in probably a very round about way) with the following:
b=sum(~isnan(A)')'>0;%Find Rows where there are non-NaN values
c= sum(isnan(A(b,:)))>0; %in those rows find the NaN values
d=mean(A(b,~c)')'; %Find the mean of the entire rows identified in c
A(b,c)= repmat(d,1,sum(c)) %Fill in the appropriate cells
Where I am getting stuck is:
Firstly: Taking the mean of only the adjacent cells in the row rather than the whole row
Secondly: Only replacing NaN values where they are surrounded on both sides with non-NaN values
i.e. A =
NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN
NaN 6 NaN NaN NaN NaN NaN
5 14 NaN NaN NaN 36 NaN
13 15 NaN NaN NaN 44 4
21 NaN NaN NaN NaN 3 12
22 31 NaN NaN NaN 11 20
>>
to
A =
NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN
NaN 6.0000 NaN NaN NaN NaN NaN
5.0000 14.0000 25.0000 25.0000 25.0000 36.0000 NaN
13.0000 15.0000 29.5000 29.5000 29.5000 44.0000 4.0000
21.0000 12.0000 12.0000 12.0000 12.0000 3.0000 12.0000
22.0000 31.0000 21.0000 21.0000 21.0000 11.0000 20.0000
>>
Thanks Again

Products

Tags

Community Treasure Hunt

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

Start Hunting!