How to replace consecutive nans elements with the line above

I have the following matrix

A = [ 0 0 0 0 1 -1 NaN NaN NaN NaN 0 0 NaN NaN NaN NaN] 

I want to replace all the NaN lines with the lines above it. For the above matrix, it will be

 A = [0 0 0 0 1 -1 1 -1 1 -1 0 0 0 0 0 0] 
+4
source share
2 answers

I'm not sure if this can be vectorized ... a simpler solution would probably be a loop:

 newRow = []; nans = isnan(A(:,1)); for ii = 1:size(A,1) if nans(ii) %# first row might be NaN -- skip it if ii==1 continue; end %# for all other rows: if isempty(newRow) newRow = A(ii-1,:); end A(ii,:) = newRow; else newRow = []; end end 
+2
source

One idea is to first create a compressed matrix B that does not contain a row with NaN , and then redeploy this matrix with the same length as the original matrix:

 mask = any(isnan(A), 2); B = A(~mask, :); result = B(cumsum(~mask), :); 
+4
source

All Articles