joe black
joe black

Reputation: 67

how to replace consecutive nans elements with the row 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 rows with the rows above it. For the matrix above, this would be

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

Upvotes: 4

Views: 174

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

I'm not sure whether this can be vectorized...the 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

Upvotes: 2

Mehrwolf
Mehrwolf

Reputation: 8537

One idea is to first create a compressed matrix B, which does not contain the rows with a NaN and then expand this matrix again to be of the same length as the original matrix:

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

Upvotes: 4

Related Questions