How to remove variable amount of consecutive NaN values from vector in Matlab?

interpolation, matlab

Solution

First of all, find the positions and lengths of all sequences of `NaN` values:

nan_idx = isnan(x(:))';
nan_start = strfind([0, nan_idx], [0 1]);
nan_len = strfind([nan_idx, 0], [1 0]) - nan_start + 1;

Next, find the indices of the `NaN` elements not to interpolate:

thr = 3;
nan_start = nan_start(nan_len > thr);
nan_end = nan_start + nan_len(nan_len > thr) - 1;
idx = cell2mat(arrayfun(@colon, nan_start, nan_end, 'UniformOutput', false));

Now, interpolate everything and replace the elements that shouldn't have been interpolated back with `NaN` values:

x_new = interp1(find(~nan_idx), x(~nan_idx), 1:numel(x));
x_new(idx) = NaN;

Problem

I have a vector of values such as the following: ``` 1 2 3 NaN 4 7 NaN NaN 54 5 2 7 2 NaN NaN NaN 5 54 3 2 NaN NaN NaN NaN 4 NaN ``` How can I use interp1 in such way that only a variable amount of consecutive NaN-values would be interpolated? That is for example I would want to interpolate only those NaN-values where there are at most three consecutive NaN-values. So NaN, NaN NaN and NaN NaN NaN would be interpolated but not NaN NaN NaN NaN. Thank you for any help =) P.S. If I can't do this with interp1, any ideas how to do this in another way? =) To give an example, the vector I gave would become: ``` 1 2 3 interpolated 4 7 interpolated interpolated 54 5 2 7 2 interpolated interpolated interpolated 5 54 3 2 NaN NaN NaN NaN 4 interpolated ```

Original source