在Matlab中用矩阵内的值替换最接近Nan的值 [英] Replacing values closest to Nan with a value, within a matrix, in Matlab

查看:1081
本文介绍了在Matlab中用矩阵内的值替换最接近Nan的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Matlab的新手,我有一个矩阵:

I am new to Matlab and I have a matrix:

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年的值.我知道如何手动进行操作,并且一步一步地进行操作.是否可以创建一个循环来查找这些值并替换它们?结果应如下所示:

I want to replace values closest to Nan with a value of 2010. I know how to do it manually and one by one. 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];

谢谢.

推荐答案

可以不定义任何显式循环.下面是步骤和示例代码.

It is possible without defining any explicit loops. Below are the steps and sample code.

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

这篇关于在Matlab中用矩阵内的值替换最接近Nan的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆