How can I replace NaN elements with the nearest value in the same column?

I am trying to replace NaN's in a vector field with the nearest value.
% I have:
M=
NaN 12
18 14
NaN NaN
NaN NaN
NaN 16
12 NaN
12 NaN
NaN 12
16 NaN
%I desire:
M=
18 12
18 14
12 16
12 16
12 16
12 12
12 12
16 12
16 12
Any information will be helpful. Thank you

댓글 수: 2

AstroGuy1984
AstroGuy1984 2017년 4월 25일
편집: AstroGuy1984 2017년 4월 25일
What do you mean by "nearest"? Do you mean "next good value"? Because that's what you appear to desire. For example the second NaN in column 1 is closer to 18 than 12.
I would like to have the first value of NaN to have the value of the next good value. However if the last value in the column is a NaN I would like for it to have the value of the previous good value

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 4월 25일
편집: Andrei Bobrov 2017년 4월 26일
FIXED 2
m = flipud(M)
t = ~isnan(m);
ii = cumsum(t);
ii(ii == 0) = 1;
ii = bsxfun(@plus,[0,ii(end,1:end-1)],ii);
m1 = m(t);
out = flipud(m1(ii))

댓글 수: 6

I keep getting an error of: Undefined function 'flip' for input arguments of type 'double'.
You are using an older version of MATLAB. Fixed for you.
Yeah I just realized that. However now I get Error using + Matrix dimensions must agree.
>> m = flipud(M);
t = ~isnan(m);
ii = cumsum(t);
ii(ii == 0) = 1;
ii = bsxfun(@plus,[0,ii(end,1:end-1)],ii);
m1 = m(t);
out = flipud(m1(ii))
out =
18 12
18 14
12 16
12 16
12 16
12 12
12 12
16 12
16 12
>>
sal135
sal135 2017년 4월 26일
편집: sal135 2017년 4월 27일
Thank you for your help! This worked out great.

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

카테고리

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

태그

질문:

2017년 4월 25일

편집:

2017년 4월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by