MATLAB: Constrain surf() plot region

cropif statementsurf

Hi all, I'm working with the surf(X,Y,Z) function, and trying to force some values to be specific. I'm basically trying to plot a 3D sin-wave, rotationally symmetric about (0,0) and contain a specific number of waves in any direction, then outside this region, force the Z values to zero. Here's code attempts using an 'if' but the Z=0 isn't applied at larger radii than Xmax:
NumberWaves = 2;
Each_Division = 0.1;
X_max = NumberWaves * (2 * pi) ;
X_min = -X_max;
Y_min = X_min;
Y_max = X_max;
[X,Y] = meshgrid(X_min : Each_Division : X_max);
Rad = sqrt (X.^2 + Y.^2 );
if (Rad < X_max)
Z=0;
else
Z = (((sin(Rad)) + 1) / 2);
end
figure;
colormap hsv;
surf(X,Y,Z, 'EdgeColor' ,'None');
xlabel('X (**)');ylabel('Y (**)');zlabel('Red Scale');
Alternatively to the forcing Z to a value, I was trying to find references to only plot the surface out to a given radius, which again would be rotationally symmetric. I'm very new to Matlab, so any help appreciated! Thanks!

Best Answer

I would recommend setting up your grid in polar coordinates. The surf command (along with mesh, pcolor, etc.) doesn't require a rectilinear grid, so starting in terms of r and theta allows you to set the cutoff exactly without any setting-to-0 or NaN-masking:
NumberWaves = 2;
Each_Division = 0.1;
rmax = NumberWaves * (2 * pi) ;
r = linspace(0, rmax, 50);
theta = linspace(0, 2*pi, 100);
[r,theta] = meshgrid(r, theta);
z = (sin(r) + 1)./2;
x = r .* cos(theta);
y = r .* sin(theta);
surf(x,y,z);