MATLAB: Replace NaNs with next real value.

findlogical?matrix manipulation

How can I replace all NaN values in an array with the next non-NaN value in the array? I have
x = [NaN 1 1 3 NaN NaN 4];
and I'd like to turn x into
x = [1 1 1 3 4 4 4];
The following works, but I'd like to do it with fewer moving parts:
for k = find(isnan(x))
x(k) = x(find(1:length(x)>k & isfinite(x),1,'first'));
end

Best Answer

Thanks for your suggestions, y'all. It's nice that R2014b has the 'next' and 'previous' options for 1D interpolation. I ended up writing a function to do the job in old 2012b.