Here the commented solution works only for the vector, but can be extended to work on the matrix:
A = [NaN NaN 1 2 3 NaN NaN 2 NaN NaN NaN 3 NaN 5 NaN NaN]; % start/end positions of NaN sequences sten = diff([0 isnan(A) 0]); B = [NaN A]; % replace with previous non NaN B(sten == -1) = B(sten == 1); % Trim first value (previously padded) B = B(2:end);
Comparison
A: NaN NaN 1 2 3 NaN NaN 2 NaN NaN NaN 3 NaN 5 NaN NaN B: NaN NaN 1 2 3 NaN 3 2 NaN NaN 2 3 3 5 NaN 5
source share