MATLAB: Interpolate NaNs only if less than 4 consecutive NaNs

selective interpolation

Hello,
I have a vector of datapoints containing some NaNs. I'd like to interpolate the NaNs only if there are 3 or less consecutive NaNs. i.e. interpolate over short datagaps but not long ones.
Any ideas would be welcome. Thanks

Best Answer

% Interpolate all NaN blocks at first:
data = [ 3 4 5 6 NaN 5 4 3 NaN NaN NaN NaN 18 20 21 NaN NaN 24 23];
nanData = isnan(data);
index = 1:numel(data);
data2 = data;
data2(nanData) = interp1(index(~nanData), data(~nanData), index(nanData));
[EDITED, Jan, 15-Sep-2013] The following does not work!
% Clear the long NaN blocks afterwards:
longBlock = strfind(data, NaN(1, 4)); % Does this work?!
index2 = zeros(1, numel(data));
index2(longBlock) = 1;
index2(longBlock + 3) = -1;
index2 = cumsum(index2);
data2(index2(1:numel(data)) ~= 0) = NaN; % Catch trailing NaNs
There are some related submission in the FEX: FEX search: inpaintnan.