How can I format the output of a for loop as a matrix so I can apply surf?
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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
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
More Answers (0)
See Also
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!