3

As I understand it, this is the basic usage of np.meshgrid:

import numpy as np
x = np.linspace(0, 1, 5)
y = np.linspace(0, 1, 5)
xx, yy = np.meshgrid(x, y)
z = xx * yy
plt.contourf(x,y,z)
plt.show()

Where xx is:

[[0.   0.25 0.5  0.75 1.  ]
 [0.   0.25 0.5  0.75 1.  ]
 [0.   0.25 0.5  0.75 1.  ]
 [0.   0.25 0.5  0.75 1.  ]
 [0.   0.25 0.5  0.75 1.  ]]

And yy is the transpose (in this case, at least).

What is not clear to me is why we need two separate 5x5 arrays. For example, why not use a 25x2 representation:

[[ 0.  , 0.  ],
 [ 0.  , 0.25],
 [ 0.  , 0.5 ],
... (etc)

Or even a 5x5x2 array.

Is there any clear advantage to using coordinate matrices? Linear algebra is a weak spot for me, so it's entire possible I'm missing something here.


Edit: I disagree with the duplicate tag. My question was more, "why is the output this strange format?", as opposed to "why would I want a meshgrid in the first place?"

With that said, I think Paul's comment mostly answers my question: In particular, the coordinate matrices make for cleaner vectorized operations when computing some z = f(x, y).

Eric V
  • 31
  • 4
  • 1
    Doesn't your example answer your question? For typical ways of working on the coordinates it is most convenient having them as arrays x and y because then as long as your operations are vectorized any code originally made for a single x and a single y will work unchanged (in theory). – Paul Panzer Dec 27 '20 at 14:19
  • Okay, I think I get it. For more "mathy" functions like f(x, y), it definitely makes sense to keep them separate. For other applications (like a classifier), it seems like a clean way to create that 25x2 grid after calling ravel(). – Eric V Dec 27 '20 at 16:57
  • `meshgrid` gives a perfectly good example using `plt.contour`. It's easy to convert the tuple of (5,5) arrays into a (5,5,2), or the (25,2). `np.mgrid` can be used to make a (2,5,5) array. `meshgrid` itself provides a couple of variants. – hpaulj Dec 27 '20 at 18:22

0 Answers0