Search code examples
matlabnanfill

Replace NaN sequence according to values before and after the sequence


I would appreciate if someone can help me with this problem...

I have a vector

A = [NaN 1 1 1 1 NaN NaN NaN NaN NaN 2 2 2 NaN NaN NaN 2 NaN NaN 3 NaN NaN];

I would like to fill the NaN values according to this logic.

1) if the value that precedes the sequence of NaN is different from the one that follows the sequence => assign half of the NaNs to the first value and half to the second value

2) if the NaN seqence is between 2 equal values => fill the NaN with that value.

A should be then:

A = [1 1 1 1 1 1 1 (1) 2 2 2 2 2 2 2 2 2 2 3 3 3] 

I have put one 1 within brakets because I assigned that value to the first half...the sequence of NaNs is odd.


Solution

  • I am typing this in my phone, without MATLAB - so there can be some issues. But this should be close:

    t = 1:numel(A);
    Anew = interp1(t(~isnan(A)),A(~isnan(A)),t,'nearest','extrap');