MATLAB: Surface plot above a non-rectangular region

non-rectangular surface plot

I'd like to draw the graph of a function above a polygonal region, which is not rectangular. Any idea how to do this? I've seen that there is a file called polygrid
https://uk.mathworks.com/matlabcentral/fileexchange/41454-grid-of-points-within-a-polygon
that extract a list of points from a polygonal region (specified by its list of vertices in the clockwise order). I intended to use the output from polygrid as my mesh for the surf function, but I haven't been able to use them compatibly. Any help will be appreciated.

Best Answer

You can simply create a binary mask of the polygon region and set all Z values to NaN outside the mask. NaN values are not plotted by surface.
%draw poly MASK/get it from your function
imagesc(Z)
Masksize=size(Z);
[x,y]=meshgrid(1:Masksize(2),1:Masksize(1));
poly=drawpolygon;
[in,on] =inpolygon(x(:),y(:),poly.Position(:,1),poly.Position(:,2));
mask=reshape(in|on,Masksize); % all points inside or on the polygon
%set all points outside mask NaN
Z(~mask)=NaN;
clf,surface(X,Y,Z)