MATLAB: Filling the gaps in a vector

nanvector

I have a vector of nans
A=[nan;nan;2;nan;4;nan;nan;nan;7;nan;nan;nan;nan] how can I fill the nan gaps by the closest number (for beginning and mid values it is the closest upper;for the last values it is the closest lower value). i,e how can reproduce the vector to become A=[2;2;2;4;4;7;7;7;7;7;7;7;7]

Best Answer

A=[nan;nan;2;nan;4;nan;nan;nan;7;nan;nan;nan;nan];
b = ~isnan(A);
k = cumsum(flipud(b));
k(k==0) = 1;
n = flipud(A(b));
s = n(k);
out = flipud(s);
or
t = ~isnan(A);
k = find(t) + 1;
z = zeros(size(A));
z(k(k <= numel(A))) = 1;
q = cumsum(z) + 1;
q(q > nnz(t)) = max(q) - 1;
p = A(t);
out = p(q);