Using interp2 in Matlab with NaN inputs

╄→гoц情女王★ 提交于 2019-11-30 16:08:02

Sorry the quick fix I gave in comment does not work directly for 2D data (it does work that simply with interp1 though, if you ever need it).

For gridded data, if you have NaNs in your grid then you do not have a uniform grid and you cannot use interp2 directly. In this case you have to use griddata first, to re-interpolate your data over a uniform grid (patch the holes basically).

(1) Let's show an example inspired from the Matlab doc:

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

(2) Now let's fix your data on a clean grid:

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

(3) Once your grid is uniform, you can then use interp2 if you want to mesh on a finer grid for example:

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


However, note that if this is all what you wanted to do, you could also use griddata only, and do everything in one step:

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

This produces the exact same grid and data than we obtained on step (3) above.


Last note: In case your NaNs are on the border of your domain, by default these functions cannot "interpolate" values for these border. To force them to do so, look at the extrapolation options of these functions, or simply interpolate on a slightly smaller grid which doesn't have NaN on the border.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!