0
$\begingroup$

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?

  • 0
    [Searching the docs is always a good idea.](http://www.mathworks.com/help/techdoc/ref/surf.html)2012-08-07

1 Answers 1

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.

  • 0
    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.2012-08-07
  • 0
    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?2012-08-07
  • 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.2012-08-07
  • 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.2012-08-07
  • 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.2012-08-07
  • 0
    @RodyOldenhuis Thanks for the verification :)2012-08-07