torch.expand_as
function expand_as<S extends Shape, T extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>, other: Tensor<T>): Tensor<ExpandShape<S, T>, D, Dev>function expand_as(input: Tensor, other: Tensor): TensorExpands tensor to match shape of another tensor.
Shorthand for expanding input to have the same shape as the other tensor. Uses expand() internally (view-based, memory efficient). Useful for:
- Shape matching: making tensors same shape without knowing target shape
- Operator broadcasting: preparing operands for element-wise ops
- Template matching: matching shape of reference tensor
- Dynamic shapes: when target shape isn't known statically
- View-based: No copy, just stride adjustment
- Other's shape: Exactly matches other.shape
- Memory efficient: Same benefits as expand()
Parameters
Returns
Tensor<ExpandShape<S, T>, D, Dev>– A view of input expanded to other's shapeExamples
// Match shape of another tensor
const a = torch.randn(1, 5, 1);
const b = torch.randn(3, 5, 4);
const expanded = torch.expand_as(a, b); // [3, 5, 4] same as b
// Element-wise operation shape matching
const scalar = torch.tensor(2).reshape([1, 1, 1]);
const matrix = torch.randn(10, 10, 10);
const broadcasted = torch.expand_as(scalar, matrix); // [10, 10, 10]See Also
- PyTorch torch.expand_as()
- expand - Expand to specific shape
- broadcast_to - Similar with prepending