[Math] Making sense out of plotting 3D graphs in octave/matplotlib

graphing-functionsMATLABoctave

Recently I have a few times I wanted to plot 3D graphs in some applications (tried matplotlib and octave), noticing similar syntax, but I don't understand what it does so its hard to modify it according to my needs. Here an octave example:

 tx = ty = linspace (-8, 8, 41)';
 [xx, yy] = meshgrid (tx, ty);
 r = sqrt (xx .^ 2 + yy .^ 2) + eps;
 tz = sin (r) ./ r;
 mesh (tx, ty, tz);

What does meshgrid, r, tz do/refer to? Suppose I want to plot something like

f(x,y) = x^2 - y^2+2xy^2 +1 

How might I do that?

Best Answer

meshgrid, as its name suggests, returns a grid of points at which you can evaluate your function. In your example xx and yy are 41x41 matrices. I can't print them here so let me use a simpler example: [xx, yy] = meshgrid (-1:1, 10:10:30). This returns

xx =

-1     0     1
-1     0     1
-1     0     1


yy =

10    10    10
20    20    20
30    30    30

Can you see how xx and yy allow you to generate every point in the grid? (Mentally pick a row/column pair; take the $x$ value from xx and the $y$ value from yy.)

To calculate function, $f(x,y)=x^2 - y^2+2xy^2 +1$, we need to bear in mind that xx and yy are matrices, so we need to use dots for element-wise multiplication, as follows:

f = xx.^2 - yy.^2 + 2*xx.*yy.^2 + 1

Finally, we plot the function using surf(xx,yy,f):

Surface plot of the function f(x,y)=x^2 - y^2+2xy^2 +1

(Note that I used the original linspace (-8, 8, 41) grid rather than the one in my previous example to generate this plot.) surf is like mesh except that it uses shading. You will immediately understand the difference if you try it for yourself.

What's going on in the Octave code is that the author was worried about division by zero (since the function to be plotted, tz is $\sin(r)/r$), so (s)he added a small number (eps) to r to ensure positivity. You do not have such a problem so our definition was more straightforward.

Related Question