Matlab "interp2" problem regarding NaN at edges

13,074

The reason they are nans is that there is no data before and after your grid to interpolate to. Linear interpolation uses the gradient of the field at the Xi,Yi, in order to estimate the value at that point. If there is nothing either side, it can't.

You can use extrapval parameter to extrapolate outside the X,Y you specify. Just add the parameter 0 after 'linear':

interp2(X,Y,tmin(:,:),Xi,Yi,'linear', 0);

This will put zero for the points 'on the edge'. However, it is likely that for points outside, they may fall off to some default value, like zero. To do this, you can add zeros before and after tmin:

tmin_padded = [  zeros(1,size(tmin,2)+2)
                zeros(size(tmin,1),1) tmin  zeros(size(tmin,1),1)
                zeros(1,size(tmin,2)+2)  ];

(haven't checked this but you get the idea.) you will also need to add some pre- and post-values to X and Y.

Use some other value, if that's the 'outside' or 'default' value of tmin.

PS why are you creating tmin_interp as 3-dimensional?

Share:
13,074
FoxRyerson
Author by

FoxRyerson

Updated on June 04, 2022

Comments

  • FoxRyerson
    FoxRyerson almost 2 years

    I am a bit stuck on a simple exercise and would appreciate some help.

    I am trying to do some simple 2D interpolation using the "interp2" function in Matlab for a variable 'tmin' of dimension [15x12]:

    lat = 15:1.5:32;
    lon = 70:1.5:92;
    
    lat_interp = 15:1:32;
    lon_interp = 70:1:92;
    
    [X,Y]   = meshgrid(lat,lon);
    [Xi,Yi] = meshgrid(lat_interp,lon_interp);
    
    tmin_interp = zeros(length(lon_interp),length(lat_interp),Num_Days);
    tmin_interp(:,:) = interp2(X,Y,tmin(:,:),Xi,Yi,'linear');
    

    This code results in the last row and last column of tmin_interp to be NaNs, i.e.:

    tmin_interp(23,1:18) ==> NaN
    tmin_interp(1:23,18) ==> NaN
    

    Does anyone know what I might be doing wrong? Am I making a simple mistake with regards to the interpolation setup? Thank you for your time.