Using interp2 in Matlab with NaN inputs

前端 未结 1 1657
清酒与你
清酒与你 2021-01-03 12:57

I have some observational data that is relatively complete, but contains some NaN values, in an matrix in matlab and I want to interpolate them to a more evenly

相关标签:
1条回答
  • 2021-01-03 13:18

    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 ;
    

    grid hole

    (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 ) ;
    

    fixed grid

    (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
    

    finer grid


    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.

    0 讨论(0)
提交回复
热议问题