MATLAB: How to replace NaN elements with the nearest value in the same column

nanreplace

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

Best Answer

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))