MATLAB Answers

Filling the gaps in a vector

5 views (last 30 days)
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]

  0 Comments

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 23 Jan 2013
Edited: Andrei Bobrov on 23 Jan 2013
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);

  0 Comments

Sign in to comment.

More Answers (3)

Image Analyst
Image Analyst on 23 Jan 2013
Do you have the Image Processing Toolbox? If so, you can use imdilate, if you're clever about it.

  1 Comment

joseph Frank
joseph Frank on 23 Jan 2013
Currently I don't but I will check with the university I think they have it

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 23 Jan 2013
Edited: Azzi Abdelmalek on 23 Jan 2013
A=[nan;nan;2;nan;4;nan;nan;nan;7;nan;nan;nan;nan]
B=A;
idx=find(isnan(A));
idx1=fliplr(find(~isnan(A)));
for k=1:numel(idx)
a=idx(k);
[~,ii]=min(abs(a-idx1));
B(idx(k))=A(idx1(ii));
end

  1 Comment

joseph Frank
joseph Frank on 24 Jan 2013
there is one additional 4

Sign in to comment.


Walter Roberson
Walter Roberson on 23 Jan 2013
You might also be interested in John D'Errico's FEX contribution inpaint_nans

  0 Comments

Sign in to comment.

Tags