用第一个非纳米值替换nans(列式)

时间:2012-06-19 07:48:46

标签: performance matlab matrix replace nan

假设我有以下矩阵 a =

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

我需要用第一个非纳米元素(列式)替换所有纳米值。所需的新矩阵应该是: b =

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

有关如何以一般方式执行此操作的任何想法? 提前谢谢Marios

1 个答案:

答案 0 :(得分:1)

定义示例数据:

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