mario
mario

Reputation: 75

replace nans with the first following non nan value (column - wise)

suppose I have the following matrix a =

 2   NaN   NaN
 4   NaN     3
 3     7     9
 5    12     5
 8    10     8
12     5    10

I need to replace all nan values with the first following non-nan element(column wise). The desired new matrix should be: b =

 2     7     3
 4     7     3
 3     7     9
 5    12     5
 8    10     8
12     5    10

Any ideas on how to do this in a general way? Thank you in advance, Marios

Upvotes: 0

Views: 589

Answers (1)

nrz
nrz

Reputation: 10560

Define the example data:

a = [
2 NaN NaN;
4 NaN 3;
3 7 9;
5 12 5;
8 10 8;
12 5 10;
];

% Here's the code:

b = a;

% Loop through all columns and all rows from bottom to top.
% If current element is not NaN and the element above is NaN,
% copy the value of current element to element above.
% If there are consecutive NaNs in the bottom of any column, they are not changed.

for colIndex = 1:size(b,2)
    for rowIndex = size(b,1):-1:2
        CurrentValue = b(rowIndex, colIndex);
        if ~isnan(CurrentValue) && isnan(b(rowIndex-1, colIndex))
            b(rowIndex-1, colIndex) = CurrentValue;
        end
    end
end

Upvotes: 1

Related Questions