简体   繁体   English

在Matlab中用矩阵内的值替换最接近Nan的值

[英]Replacing values closest to Nan with a value, within a matrix, in Matlab

I am new to Matlab and I have a matrix: 我是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];

I want to replace values closest to Nan with a value of 2010. I know how to do it manually and one by one. 我想将最接近Nan的值替换为2010年的值。我知道如何手动进行操作,并且一步一步地进行操作。 Is there any to create a loop to find these values and replace them? 是否可以创建一个循环来查找这些值并替换它们? The result should look like this: 结果应如下所示:

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];

Thank you in advance. 先感谢您。

Thanks to @crazyGamer for improving the answer with explanations and clearer variable names. 感谢@crazyGamer通过解释和更清晰的变量名来改善答案。


You can use 2D-convolution to detect entries that are close to a NaN ; 您可以使用2D卷积来检测接近NaN条目; select non- NaN 's among those entries, and write the desired value there. 在这些条目中选择非NaN ,然后在其中写入所需的值。

Closeness is defined by means of a neighbourhood binary mask. 紧密度通过邻域二进制掩码定义。 This usually has 4 neighbours (up, down, left, right) or 8 (including diagonals). 通常有4邻居(上,下,左,右)或8 (包括对角线)。

The code is generalized to use either mask as per choice. 该代码被通用为根据选择使用任一掩码。

Solution

% 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;

It is possible without defining any explicit loops. 无需定义任何显式循环是可能的。 Below are the steps and sample code. 下面是步骤和示例代码。

  • Use the find function to determine which elements are NaN . 使用find函数确定哪些元素为NaN
  • Then, offset those indices by 1 both in the positive and negative direction to find positions of neighboring elements. 然后,将这些索引在正方向和负方向上都偏移1,以找到相邻元素的位置。
  • Finally replace all such locations with required value, after deleting those positions that are outside the array. 删除数组外部的位置后,最后用所需的值替换所有此类位置。

Sample code 样例代码

% 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM