Why is meshgrid useful? Particularly, why are coordinate matrices valuable over other representations (like simple arrays)?

Viewed 83

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).

0 Answers
Related