0

假设我有以下矩阵 a =

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

我需要用以下第一个非 nan 元素(按列)替换所有 nan 值。所需的新矩阵应为: b =

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

关于如何以一般方式执行此操作的任何想法?提前谢谢你,马里奥斯

4

1 回答 1

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
于 2012-06-19T08:01:09.473 回答