Search code examples
matlabinterpolation

How to use ndgrid with interp2


Matlab infamously has two functions for creating gridded data, ndgrid and meshgrid. meshgrid is very annoying because it mixes up rows and columns whereas ndgrid keeps it consistent. So I like to stick with ndgrid.

But it turns out, in order to interpolate using interp2, I need meshgrid style gridded data. But the rest of my code cannot handle if I used meshgrid, I want to stick to ndgrid. How do I make ndgrid work with interp2, and what is the method to this madness? I am sick of randomly transposing matrices until the code works.

[X, Y]=ndgrid(0:0.1:1,0:0.1:2);
F=cos(X).*sin(Y);
[X2, Y2]=ndgrid(0:0.05:1,0:0.05:2);
F2=interp2(X,Y,F,X2,Y2);

I know there is a way to get this to work by transposing bunch of stuff, what is the right way to do this? It is so immensely confusing when ndgrid and meshgrid are flipping rows and columns around, there has to be a "right way" to navigate this. Over the course of past six years, I have been brought to tears by the frustration caused by ndgrid and meshgrid flipping around rows and columns.


Solution

  • Try griddedIntepolant, which makes ndgrid-like assumptions. For your example:

    [X, Y]=ndgrid(0:0.1:1,0:0.1:2);
    Z=cos(X).*sin(Y);
    F=griddedInterpolant(X, Y, Z);
    [X2, Y2]=ndgrid(0:0.05:1,0:0.05:2);
    Z2=F(X2,Y2);
    

    If you need to use interp2 for 2-D cases like your example, then it suffices to know that [X, Y]=ndgrid(x,y) is equivalent to [Y, X]=meshgrid(y,x). So for your example, you could do:

    [X, Y]=ndgrid(0:0.1:1,0:0.1:2);
    F=cos(X).*sin(Y);
    [X2, Y2]=ndgrid(0:0.05:1,0:0.05:2);
    F2=interp2(Y,X,F,Y2,X2);
    

    Lastly, this is supposedly the general method to covert from meshgrid to ndgrid in 3-D.