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 examplexx
andyy
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 returnsCan you see how
xx
andyy
allow you to generate every point in the grid? (Mentally pick a row/column pair; take the $x$ value fromxx
and the $y$ value fromyy
.)To calculate function, $f(x,y)=x^2 - y^2+2xy^2 +1$, we need to bear in mind that
xx
andyy
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)
:(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 likemesh
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
) tor
to ensure positivity. You do not have such a problem so our definition was more straightforward.