Speed ​​up replacing NaNs with last value other than Nan

I would like to replace all NaN in the vector with the last previous value other than NaN

input = [1 2 3 NaN NaN 2]; output = [1 2 3 3 3 2]; 

I would like to speed up the cycle that I already have

 input = [1 2 3 NaN NaN 2]; if isnan(input(1)) input(1) = 0; end for i= 2:numel(input) if isnan(input(i)) input(i) = input(i-1); end end 

early

+4
source share
4 answers

Since you want a previous value other than NaN, I will assume that the first value should be a number.

 while(any(isnan(input))) input(isnan(input)) = input(find(isnan(input))-1); end 

I profiled the solution of Dylan, the solution of Oleg and mine on 47.7 million long vectors. The time was 12.3 s for dylan, 3.7 for Oleg and 1.9 for mine.

+2
source

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 
0
source

Not fully vectorized, but quite simple and probably still quite efficient:

 x = [1 2 3 NaN NaN 2]; for f = find(isnan(x)) x(f)=x(f-1); end 

Of course, this is slightly different from the solution provided by @Hugh Nolan

0
source
 nan_ind = find(isnan(A)==1); A(nan_ind) = A(nan_ind-1); 
-1
source

Source: https://habr.com/ru/post/1487512/


All Articles