PyTorch torch.cross function
PyTorch torch reference manual
torch.cross is a PyTorch function for computing the cross product of two 3D vectors (or batches of 3D vectors). The cross product produces a new vector perpendicular to both input vectors.
Function definition
torch.cross(input, other, dim=-1)
Usage examples
Example
import
torch
Cross product of two 3D vectors
a
=
torch.
tensor
(
[
1
,
0
,
0
]
)
b
=
torch.
tensor
(
[
0
,
1
,
0
]
)
c
=
torch.
cross
(
a
,
b
)
(
"a:"
,
a
)
(
"b:"
,
b
)
(
"a x b:"
,
c
)
Output: tensor([0, 0, 1])
Batch computation of cross products
a
=
torch.
tensor
(
[
[
1
,
0
,
0
]
,
[
0
,
1
,
0
]
]
)
b
=
torch.
tensor
(
[
[
0
,
1
,
0
]
,
[
1
,
0
,
0
]
]
)
result
=
torch.
cross
(
a
,
b
)
(
"Batch cross product:"
)
(
result
)
tensor([[0, 0, 1],
[0, 0, -1]])
Specify a dimension
a
=
torch.
randn
(
3
,
4
,
3
)
b
=
torch.
randn
(
3
,
4
,
3
)
result
=
torch.
cross
(
a
,
b
,
dim
=
2
)
(
"Shape of cross product along specified dimension:"
,
result.
shape
)