PyTorch torch.meshgrid Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.meshgridIt 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 tensor
  • indexing: Indexing mode, 'xy' (Cartesian) or 'ij' (matrix)

Example Usage

Example

import torch

# Create coordinate vectors
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5])

# Create meshgrid (Cartesian indexing)
grid_x, grid_y = torch.meshgrid(x, y, indexing='xy')
print("grid_x:")
print(grid_x)
print("grid_y:")
print(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 meshgrid (matrix indexing)
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
print("grid_x:")
print(grid_x)
print("grid_y:")
print(grid_y)

The output is:

grid_x:
tensor([[1, 1],
        [2, 2],
        [3, 3]])
grid_y:
tensor([[4, 5],
        [4, 5],
        [4, 5]])

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions