0

I'd like to draw a monkey saddle surface using matlab. But how do I plot a function of several variables in matlab? I never did that before. I can define $x$ and $y$ as two vectors and then according to wikipedia the monkey saddle equation is $x^3-3xy^2$ so all I wanna do is plot that function? Are there any more monkey saddle surfaces that might be nicer than this one?

Emily
  • 35,688
  • 6
  • 93
  • 141

1 Answers1

1

The easiest way is to use the surf command:

x = min_x:step:max_x;
y = min_y:step:max_y;

[X,Y] = meshgrid(x,y);

Z = X.^3-3*X.*Y.^2

surf(X,Y,Z);

should work. I don't have my MATLAB install on this computer, so I cannot verify.

Emily
  • 35,688
  • 6
  • 93
  • 141
  • Note that surf requires that the inputs be matrices, so this limits your resolution. This is a big frustration of mine, since X is a single row vector repeated a bunch of times, and Y is a single column vector repeated a bunch of times. – Emily Aug 07 '12 at 13:27
  • Thank you, it looks like I almost can do it now but I don't understand the meshgrid part and the equation you write looks a little bit different than what I expected. I tried between -10 and 10 for both x and y with step 0.5 and put in the equation just like x=x^3-3*x*y^2 but the surf command then displayed just a flat surface. The points might've been off? – Niklas Rosencrantz Aug 07 '12 at 13:28
  • 1
    The meshgrid command turns $x$ and $y$ vectors into the matrix format required by surf. To generate your $Z$ surface, you need to use element-wise operations, so that's why you need to use .* and .^

    Example: x = [0 1 2]; y = [0 1 2]; Then X = [0 1 2; 0 1 2; 0 1 2]; Y = [0 0 0; 1 1 1; 2 2 2]; And you want to element-wise compute Z = X.^3-3*X.*Y.^2, which takes Z(1,1) = X(1,1)^3-3*X(1,1)*Y(1,1)^2 and so forth.

    – Emily Aug 07 '12 at 13:32
  • 1
    If you can wait an hour, I will be at a machine with MATLAB and can test this. However, I am fairly confident the above code will work as-is. – Emily Aug 07 '12 at 13:34
  • 1
    @NickRosencrantz I just verified this. Using step = 0.1 and min_x,max_x = min_y,max_y = -10,10, you get a nice smooth 3D saddle plot. I'd suggest you use 'edgecolor','none' as additional options to surf, to not drown the plot in gridlines. Your 'flat surface' results from you not using the dot-operator for element-wise multiplications. You were 'lucky' it even worked; try non-square matrices, which will give you an error. – Rody Oldenhuis Aug 07 '12 at 13:52
  • @RodyOldenhuis Thanks for the verification :) – Emily Aug 07 '12 at 14:25