How can I format the output of a for loop as a matrix so I can apply surf?

1 view (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 10 Mar 2015
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
  2 Comments
Tony Theis
Tony Theis on 11 Mar 2015
Edited: Tony Theis on 11 Mar 2015
Thanks for the response, but maybe my intentions weren't clear. I essentially want to define a maximum function where (to use your notation):
Z=ZF when ZF >0, and
Z= 0 when ZF <0,
and then graph Z using surf (or any other 3D graphing command) to produce a surface on the xy plane, with mounds made by the tips of the sine waves.
Star Strider
Star Strider on 11 Mar 2015
Missed that, sorry.
I believe this now does what you want:
[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).*(ZF(X,Y) > 0);
figure(1)
surf(X,Y,Z)
grid on

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!