MATLAB: How to interpolate only if 5 or less missing data next to each other

interpolate arraysinterpolationselective interpolation

Hi,
I have an array of data, I want to interpolate NaNs over columns but only if there is 5 or less consecutive NaNs in a column.
I was thinking of using isnan function, and then marking places where I need to interpolate, but I'm not sure exactly how to do that.
Any ideas are welcom 🙂 Thanks!
K.

Best Answer

[b, n] = RunLength(isnan(x));
shortNaN = RunLength(b & (n < 5), n);
x(shortNaN) = interp1(find(~shortNaN), x(~shortNaN), find(shortNaN), 'linear');
INTERP1 shows a warning then:
Warning: NaN found in Y, interpolation at undefined values
will result in undefined values.
But it is not possible that the NaN's appear in the output of the interpolation in this case and therefore the warning is misleading. To avoid it, you can either use a much faster replacement of INTERP1, see e.g. http://www.mathworks.com/matlabcentral/answers/64118#answer_75899 . Or you can interpolate on all NaNs at first and overwrite the long runs afterwards:
index = isnan(x);
x(index) = interp1(find(~index), x(~index), find(index), 'linear');
[b, n] = RunLength(index);
longRun = RunLength(b & (n > 4), n);
x(longRun) = NaN;