MATLAB: How to format the output of a for loop as a matrix so I can apply surf

for loopif statementMATLABpiecwisesurf

I need to create a piecewise function that I can graph using surf. The function is:
for 0<x<12pi and 0<y<12pi,
Z = sin(x) + sin(y) - 1 if z>0
0 if z<0
%not code
A for loop seems like an easy way to do this. I used:
[X,Y] = meshgrid(0:.2:(12*pi), 0:.2:(12*pi)); %defining my domain
Z = sin(X)+sin(Y)-1;
for i=X
for j=Y
if Z > 0
Z = Z;
else
Z = 0;
end
end
end
figure
surf(X,Y,Z)
which produces the errors:
Error using surf (line 57) Z must be a matrix, not a scalar or vector.
Error in model1 (line 13) surf(X,Y,Z)
(model1 is the name of my script)
Any advice? Simplicity appreciated.

Best Answer

Use an anonymous function for ‘Z’ (I created the function as ‘ZF’, and the variable as ‘Z’).
The loop is not necessary:
[X,Y] = meshgrid(0:.2:(12*pi), 0:.2:(12*pi)); %defining my domain
ZF = @(X,Y) sin(X)+sin(Y)-1;
Z = ZF(X,Y);
figure(1)
surf(X,Y,Z)
grid on