在Matlab中使用interp2和NaN输入

时间:2015-07-30 17:01:10

标签: matlab matrix interpolation

我有一些相对完整的观测数据,但在matlab的矩阵中包含一些NaN值,我希望使用interp2

将它们插入到更均匀间隔的网格中

所以,为了简单起见,我可以说我有一个完整的(没有NaN值)矩阵,而且看起来像是:

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

BC是完整矩阵,interp2不接受具有NaN值的输入矩阵。所以,如果我做这样的事情:

[AI,BI] = meshgrid(a,b) %# matrices to interpolate data to, arbitrary
CI = interp2(A,B,C,AI,BI) %# interpolation, A has NaN values

我收到错误:

Error using griddedInterpolant
The coordinates of the input points must be finite values; Inf and NaN are not permitted.

任何人都可以提出解决方案或合理的解决方法吗?

1 个答案:

答案 0 :(得分:3)

很抱歉,我在评论中提供的快速修补程序无法直接用于2D数据(它只能使用 interp1 工作,但是,如果您需要它)。

对于网格化数据,如果您的网格中有NaN,则表示您没有统一网格,并且无法直接使用interp2。在这种情况下,您必须首先使用griddata,通过统一网格重新插入数据(基本上修补漏洞)。

(1)让我们展示一个受Matlab文档启发的例子:

%% // define a surface
[A,B] = meshgrid(-3:0.25:3);
C = peaks(A,B);

%// poke some holes in it (in every coordinate set)
A(15,3:8)   = NaN ;
B(14:18,13) = NaN ;
C(8,16:21)  = NaN ;

grid hole

(2)现在让我们在干净的网格上修复您的数据:

%// identify indices valid for the 3 matrix 
idxgood=~(isnan(A) | isnan(B) | isnan(C)); 

%// define a "uniform" grid without holes (same boundaries and sampling than original grid)
[AI,BI] = meshgrid(-3:0.25:3) ;

%// re-interpolate scattered data (only valid indices) over the "uniform" grid
CI = griddata( A(idxgood),B(idxgood),C(idxgood), AI, BI ) ;

fixed grid

(3)网格一致后,如果要在更精细的网格上进行网格划分,则可以使用interp2

[XI,YI] = meshgrid(-3:0.1:3) ;   %// create finer grid
ZI = interp2( AI,BI,CI,XI,YI ) ; %// re-interpolate

finer grid

但请注意,如果这就是您想要做的所有事情,您也可以只使用griddata,并且只需一步即可完成所有操作:

%// identify indices valid for the 3 matrix 
idxgood=~(isnan(A) | isnan(B) | isnan(C)); 

%// define a "uniform" grid without holes (finer grid than original grid)
[XI,YI] = meshgrid(-3:0.1:3) ;

%// re-interpolate scattered data (only valid indices) over the "uniform" grid
ZI = griddata( A(idxgood),B(idxgood),C(idxgood), XI, YI ) ;

这产生与我们在上面步骤(3)中获得的完全相同的网格和数据。

最后注意:如果您的NaN位于您网域的边框上,默认情况下这些功能无法“插入”这些边框的值。要强制它们这样做,请查看这些函数的extrapolation选项,或者简单地在边框上没有NaN的较小网格上进行插值。