MATLAB: Trying to learn griddata function.

contourgriddatagriddingMATLABmeshgridnan

Hi I'm triyng to learn the griddata command but I always come face to facve with NaN values in the griddata function. Can anyone explain why please?
clc;clear;
x1= rand(752,1);
x2= rand(752,1);
y1= rand(752,1);
[xx,yy]=meshgrid(x1,x2);
z= griddata(x1,x2,y1,xx,yy);
contourf(xx,yy,z);

Best Answer

Your x1, x2 and xx, yy inputs do need to be unique. Since you create the vectors using rand, every once in a while you may get duplicate values, resulting in that error message.
I think your requested grid query points should be sorted.
data = rand(752,3);
x1= data(:,1);
x2= data(:,2);
y1= data(:,3);
% sorted x1, x2 inputs
[xx,yy]=meshgrid(sort(x1),sort(x2));
z= griddata(x1,x2,y1,xx,yy);
contourf(xx,yy,z);
Even here, the corners still have NaN values (more visible in a heatmap). This might be explained by this line in the documentation: "The specified query points must lie inside the convex hull of the sample data points. griddata returns NaN for query points outside of the convex hull."
heatmap(z,'GridVisible',false)
I suspect this is an artifact of using random numbers. You may get better results when using actual data.