torch.linalg.matrix_power
function matrix_power<S extends Shape, D extends DType, Dev extends DeviceType>(A: Tensor<S, D, Dev>, n: number): Tensor<S, D, Dev>Computes the n-th power of a square matrix for an integer n.
Calculates A^n by repeated matrix multiplication (for positive n), matrix inversion (for negative n), or returns identity (for n=0). Essential for:
- Iterative algorithms: Computing power updates in optimization
- Markov chains: Computing n-step transition probabilities (P^n)
- Differential equations: Matrix exponential approximations
- Dynamical systems: State propagation forward/backward in time
- Cryptography: Repeated applications (e.g., diffusion layers)
- Graph analysis: N-hop reachability in adjacency matrices
For n > 0: computes A · A · ... · A (n times) via repeated squaring. For n = 0: returns identity matrix with same shape as A. For n < 0: computes (A^-1)^(-n) using matrix inversion and repeated multiplication.
- Square matrices required: Matrix must be square (m × m)
- Repeated squaring: Implementation uses efficient algorithms for large n
- Integer powers only: No fractional powers (see matrix exponential for continuous analogs)
- Batch support: Works on batched matrices via broadcasting
- Positive n fastest: Small positive n computed fastest via direct multiplication
- Numerical instability: Very large n can cause numerical overflow/underflow
- Singular for negative n: Matrix must be invertible (non-singular) for n 0
- Computational cost: O(n·m³) for n 0; O(m³ + m³) for n 0 (invert + multiply)
Parameters
ATensor<S, D, Dev>- Square matrix or batch of matrices with shape [..., m, m]
nnumber- Integer power (positive, negative, or zero)
Returns
Tensor<S, D, Dev>– Tensor A^n with same shape as A. Scalar powers expand to full shape with identityExamples
// Positive power: A^3
const A = torch.tensor([[1, 2], [3, 4]]);
const A3 = torch.linalg.matrix_power(A, 3); // A @ A @ A
// Zero power: identity
const A0 = torch.linalg.matrix_power(A, 0); // [[1, 0], [0, 1]]
// Negative power: A^-2 = (A^-1)^2
const A_neg2 = torch.linalg.matrix_power(A, -2);
// Markov chain: n-step transition probabilities
const P = torch.tensor([[0.9, 0.1], [0.2, 0.8]]); // Transition matrix
const P_10 = torch.linalg.matrix_power(P, 10); // 10-step probabilities
// Batch operations
const A_batch = torch.randn(5, 3, 3); // 5 3x3 matrices
const A_batch_4 = torch.linalg.matrix_power(A_batch, 4); // [5, 3, 3]
// Verification: A^2 @ A = A^3
const A2 = torch.linalg.matrix_power(A, 2);
const A3_check = torch.matmul(A2, A); // Should equal torch.linalg.matrix_power(A, 3)See Also
- PyTorch torch.linalg.matrix_power(A, n)
- inv - Matrix inversion (computes A^-1)
- matmul - Matrix multiplication (used internally)
- linalg.matrix_exp - Matrix exponential (continuous analog)