我是Matlab的新手,我有一个矩阵:
M =[NaN NaN NaN 2010 5454;
NaN NaN 2009 3000 5000
NaN 2011 3256 5454 6000
2009 4000 5666 6545 5555
5000 5666 6000 7000 8000];
我想用最接近Nan的值替换值为2010.我知道如何手动并逐个进行。有没有创建一个循环来找到这些值并替换它们?结果应如下所示:
M =[NaN NaN NaN 2010 5454;
NaN NaN 2010 3000 5000
NaN 2010 3256 5454 6000
2010 4000 5666 6545 5555
5000 5666 6000 7000 8000];
提前谢谢。
答案 0 :(得分:3)
感谢@crazyGamer通过解释和更清晰的变量名来改进答案。
您可以使用2D卷积来检测接近NaN
的条目;在这些条目中选择非NaN
,并在那里写下所需的值。
通过邻域二元掩模定义接近度。这通常有4
个邻居(上,下,左,右)或8
(包括对角线)。
代码被推广为根据选择使用任一掩码。
% Data:
M = [ NaN NaN NaN 2010 5454;
NaN NaN 2009 3000 5000;
NaN 2011 3256 5454 6000;
2009 4000 5666 6545 5555;
5000 5666 6000 7000 8000 ];
neighbourhood = [0 1 0; 1 0 1; 0 1 0];
% or [1 1 1; 1 0 1; 1 1 1] for 8-neighbours
new_value = 2010;
% Computations:
nanInds = isnan(M);
nanIndsWithNeighs = conv2(nanInds, neighbourhood, 'same')~=0;
neighInds = ~nanInds & nanIndsWithNeighs; % logical AND
M(neighInds) = new_value;
答案 1 :(得分:2)
可以不定义任何显式循环。以下是步骤和示例代码。
find
功能确定哪些元素为NaN
。% Row and column indices of NaN in array `a`
[x, y] = find(isnan(a));
% All 4-neighbor elements around each NaN
r = [x-1 x+1 x x];
c = [y y y-1 y+1];
% Delete those values that are outside the array bounds
% (For NaNs in the edges)
outInd = r < 1 | r > size(a, 1) | c < 1 | c > size(a, 2);
r(outInd) = [];
c(outInd) = [];
% Replace all these neighbors with required value
a(sub2ind(size(a), r, c)) = 2010;