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

 채택된 답변

Walter Roberson
Walter Roberson 2011년 8월 3일

0 개 추천

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

댓글 수: 1

James
James 2011년 8월 3일
This looks like it might do the trick, I will give it a shot.
Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Image Analyst
Image Analyst 2011년 8월 3일

0 개 추천

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.
James
James 2011년 8월 3일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

Community Treasure Hunt

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

Start Hunting!

Translated by