MATLAB: Error in interp2: The grid vectors do not define a grid of points that match the given values

errorerror messagegrid vectorsgriddedinterpolantinterp2interpolation

I have an map z of size [512,721] and two corresponding axes x and y with 512 and 721 elements respectively. I want to interpolate the map to 1024 by 1024 points and am using interp2 for this.
I generate new axes xi and yi as follows:
x = 1:512; y = 1:721;
nx = 512; ny = 721; ni = 1024;
xi = 1:nx/ni:ni; yi = 1:ny/ni:ny;
I know that xi and yi have only 1023 elements now put at the moment I am struggling with the error I get when running interp2. So here is a short minimal example:
z = rand(n1,n2); %original 2D-map
zi = interp2(x,y,z,xi,yi);
This throws the error:
Error using griddedInterpolant
The grid vectors do not define a grid of points that match the given
values.
The same happens if I run the code with meshgrids instead of vectors:
[xm,ym] = meshgrid(x,y);
[xmi,ymi] = meshgrid(xi,yi);
zmi = interp2(xm,ym,z,xmi,ymi);
I also tried switching x and y (and xi and yi) in interp2, in which case the code runs without an error, however zmi is then a vector with 1023 elements:
zmiflipped = interp2(y,x,z,yi,xi);
all(size(zmiflipped) == [ 1,1023])
Can someone help me understand the error and explain to me how I can fix it? I am using MATLAB R2013a

Best Answer

x = 1:512;
y = 1:721;
nx = 512;
ny = 721;
ni = 1024;
xi = linspace(1,nx,ni);
yi = linspace(1,ny,ni);
[X,Y] = ndgrid(x,y);
z = rand(nx,ny);
F = griddedInterpolant(X,Y,z,'cubic');
[XI,YI] = ndgrid(xi,yi);
zi = F(XI,YI);
Plese read about griddedInterpolant.