MATLAB如何用实数值替换NaN和NaN的实数值

时间:2016-06-04 17:48:42

标签: arrays matlab nan

我有以下矩阵

xx = [ 1 2 3 4; NaN NaN 7 8]; 

我想将xx更改为:

yy = [ NaN NaN NaN NaN; 88 88 NaN NaN];

我有以下脚本

for i = 1:2;
    for j = 1:4;
        if (xx(i,j) ~= NaN)
            yy(i,j) = NaN;
        else
            yy(i,j) = 88;
        end
    end
end
xx
yy

但是我有不想要的结果,因为

yy =

   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

非常感谢你的帮助

1 个答案:

答案 0 :(得分:3)

无需循环。只需使用logical indexing

yy = xx; % initiallize yy to xx
ind = isnan(xx); % logical index of NaN values in xx
yy(ind) = 88; % replace NaN with 88
yy(~ind) = NaN; % replace numbers with NaN

无论如何,您的代码存在的问题是xx(i,j) ~= NaN始终提供true。根据定义,NaN不等于任何东西。要检查值是否为NaN,您需要isnan功能。因此,您应该在代码中使用~isnan(xx(i,j))

for i = 1:2;
    for j = 1:4;
        if ~isnan(xx(i,j))
            yy(i,j) = NaN;
        else
            yy(i,j) = 88;
        end
    end
end

另外,请考虑preallocating yy的速度。例如,您可以初始化yy,所有条目等于88,然后您可以删除else分支:

yy = repmat(88, size(xx));
for i = 1:2;
    for j = 1:4;
        if ~isnan(xx(i,j))
            yy(i,j) = NaN;
        end
    end
end