4

我想用最后一个非 NaN 值替换向量中的所有 NaN

input =  [1 2 3 NaN NaN 2];
output = [1 2 3 3   3   2];

我想尝试加快我已经拥有的循环

input = [1 2 3 NaN NaN 2];

if isnan(input(1))
    input(1) = 0;
end

for i= 2:numel(input)
    if isnan(input(i))
        input(i) = input(i-1);
    end
end

提前致谢

4

4 回答 4

2

Since you want the previous non-NaN value, I'll assume that the first value must be a number.

while(any(isnan(input)))
    input(isnan(input)) = input(find(isnan(input))-1);
end

I profiled dylan's solution, Oleg's solution, and mine on a 47.7 million long vector. The times were 12.3s for dylan, 3.7 for Oleg, and 1.9 for mine.

于 2013-06-21T19:17:00.840 回答
0

没有完全矢量化,但很简单,可能仍然相当有效:

x = [1 2 3 NaN NaN 2];
for f = find(isnan(x))
    x(f)=x(f-1);
end

当然,这与@Hugh Nolan 提供的解决方案略有不同

于 2013-07-04T13:17:24.123 回答
0

这里有一个注释的解决方案,仅适用于向量,但可能会扩展为在矩阵上工作:

A = [NaN NaN 1 2 3 NaN NaN 2 NaN NaN NaN 3 NaN 5 NaN NaN];

% start/end positions of NaN sequences
sten = diff([0 isnan(A) 0]);
B    = [NaN A];
% replace with previous non NaN
B(sten == -1) = B(sten == 1);
% Trim first value (previously padded)
B = B(2:end);

比较

A: NaN NaN 1 2 3 NaN NaN 2 NaN NaN NaN 3 NaN 5 NaN NaN
B: NaN NaN 1 2 3 NaN   3 2 NaN NaN   2 3   3 5 NaN   5
于 2013-06-21T16:50:15.020 回答
-1
nan_ind = find(isnan(A)==1);
A(nan_ind) = A(nan_ind-1);
于 2015-01-12T14:57:45.947 回答