PyTorch torch.meshgrid function
PyTorch torch reference manual
torch.meshgrid is a function in PyTorch used to create a grid from coordinate vectors. It generates coordinate tensors from multiple one-dimensional coordinate vectors.
Function definition
torch.meshgrid(*tensors, indexing='xy')
Parameter Description:
*tensors: Input one-dimensional tensorsindexing: Indexing mode, 'xy' (Cartesian) or 'ij' (matrix)
Usage examples
Example
import
torch
Create coordinate vectors
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
y
=
torch.
tensor
(
[
4
,
5
]
)
Create a grid (Cartesian indexing)
grid_x
,
grid_y
=
torch.
meshgrid
(
x
,
y
,
indexing
=
'xy'
)
(
"grid_x:"
)
(
grid_x
)
(
"grid_y:"
)
(
grid_y
)
The output is:
grid_x:
tensor([[1, 2, 3],
[1, 2, 3]])
grid_y:
tensor([[4, 4, 4],
[5, 5, 5]])
Example
import
torch
Create coordinate vectors
x
=
torch.
tensor
(
[
1
,
2
,
3
]
)
y
=
torch.
tensor
(
[
4
,
5
]
)
Create a grid (matrix indexing)
grid_x
,
grid_y
=
torch.
meshgrid
(
x
,
y
,
indexing
=
'ij'
)
(
"grid_x:"
)
(
grid_x
)
(
"grid_y:"
)
(
grid_y
)
The output is:
grid_x:
tensor([[1, 1],
[2, 2],
[3, 3]])
grid_y:
tensor([[4, 5],
[4, 5],
[4, 5]])