MATLAB: How to merge adjacent NaN values into single NaN value in a vector

nanvector

I have [1 2 3 NaN NaN 0 1 2 NaN 9 8 7 6 NaN NaN NaN 1 1] anf I want [1 2 3 NaN 0 1 2 NaN 9 8 7 6 NaN 1 1] without a for cycle. Are there any trick to do this?

Best Answer

No loops required, no tricks required, just basic MATLAB indexing:
old = [1 2 3 NaN NaN 0 1 2 NaN 9 8 7 6 NaN NaN NaN 1 1];
idx = ~isnan(old);
new = old(idx | [true,idx(1:end-1)]);