Advanced Matrix Operations with scipy.linalg.matrix_power

Advanced Matrix Operations with scipy.linalg.matrix_power

For a square matrix A, a nonnegative integer power is defined by matrix multiplication: A⁰ = I, and Aᵏ is the product of k copies of A when k > 0. The identity matrix is essential here: it has the same shape as A and satisfies AI = IA = A.

Matrix powers use matrix multiplication, not elementwise multiplication. For example, A² means A @ A in NumPy. The familiar scalar rule (ab)ᵏ = aᵏbᵏ does not generally extend to matrices: (AB)ᵏ is not usually AᵏBᵏ, because matrix multiplication is not commutative. The identity (AB)ᵏ = AᵏBᵏ does hold when A and B commute, meaning AB = BA.

import numpy as np

A = np.array([[1.0, 2.0],
              [0.0, 1.0]])
B = np.array([[1.0, 0.0],
              [3.0, 1.0]])

A2 = A @ A
product_power = (A @ B) @ (A @ B)
separate_powers = (A @ A) @ (B @ B)

assert not np.allclose(product_power, separate_powers)

Powers of a single matrix do obey the usual exponent laws for nonnegative integer exponents: AᵐAⁿ = Aᵐ⁺ⁿ and (Aᵐ)ⁿ = Aᵐⁿ. These identities follow from associativity of matrix multiplication; they do not require A to be diagonalizable.

Eigenvalues help explain how powers behave. If Av = λv, then Aᵏv = λᵏv. Thus, eigenvalues with magnitude greater than one grow under repeated powers, while eigenvalues with magnitude less than one shrink. An eigenvalue of magnitude one does not by itself guarantee bounded powers: non-diagonalizable matrices can produce polynomial growth as well.

Computing integer powers with scipy.linalg.matrix_power

scipy.linalg.matrix_power computes an integer power of a square matrix using matrix multiplication. Pass the matrix and the exponent as separate arguments; the result is a new array representing the power.

import numpy as np
from scipy.linalg import matrix_power

A = np.array([[1.0, 2.0],
              [0.0, 1.0]])

A4 = matrix_power(A, 4)
print(A4)

For a positive exponent, the function uses exponentiation by squaring rather than multiplying by A once for every increment of the exponent. This takes a number of matrix multiplications proportional to log₂(n), which matters when n is large. For example, computing the sixteenth power requires only a few squarings.

A16 = matrix_power(A, 16)

A2 = A @ A
A4 = A2 @ A2
A8 = A4 @ A4
A16_manual = A8 @ A8

assert np.allclose(A16, A16_manual)

Use matrix_power when the exponent is a single integer. It does not interpret an array of exponents as a request to compute a different power for each element, and it does not compute elementwise powers. For a collection of matrices, apply the function to each matrix explicitly.

matrices = np.stack([
    np.eye(2),
    np.array([[1.0, 1.0],
              [0.0, 1.0]])
])

squared = np.stack([matrix_power(M, 2) for M in matrices])

The multiplication order chosen by exponentiation by squaring can differ from a loop that multiplies the matrix repeatedly. In floating-point arithmetic, those evaluation orders can produce slightly different rounding errors, so compare results with a tolerance rather than exact equality.

A = np.array([[0.1, 0.2],
              [0.3, 0.4]])

fast = matrix_power(A, 12)

slow = np.eye(A.shape[0])
for _ in range(12):
    slow = slow @ A

assert np.allclose(fast, slow, rtol=1e-12, atol=1e-12)

Handling inverses, negative powers, and singular matrices

A negative integer exponent denotes a power of the inverse: A⁻ᵏ = (A⁻¹)ᵏ for positive k. The matrix must therefore be square and nonsingular. For example, matrix_power(A, -1) computes the inverse, while matrix_power(A, -3) computes the cube of the inverse.

import numpy as np
from scipy.linalg import matrix_power

A = np.array([[2.0, 1.0],
              [1.0, 1.0]])

A_inv = matrix_power(A, -1)
A_inv_cubed = matrix_power(A, -3)

assert np.allclose(A @ A_inv, np.eye(2))
assert np.allclose(A_inv_cubed, A_inv @ A_inv @ A_inv)

A singular matrix has no inverse, so a negative power is undefined. SciPy reports this with a linear-algebra error; handle that error when singularity is an expected possibility rather than allowing the computation to stop unexpectedly.

singular = np.array([[1.0, 2.0],
                     [2.0, 4.0]])

try:
    result = matrix_power(singular, -1)
except np.linalg.LinAlgError:
    result = None

A matrix can also be so close to singular that its inverse exists mathematically but is unreliable in floating-point arithmetic. In that case, small input errors can be amplified substantially. Inspecting the condition number can help identify this situation, though the appropriate threshold depends on the scale and accuracy requirements of the problem.

A = np.array([[1.0, 1.0],
              [1.0, 1.0 + 1e-12]])

print(np.linalg.cond(A))

If the goal is to apply an inverse power to a vector, forming the inverse matrix is often unnecessary. For A⁻ᵏb, solve the system Ax = b repeatedly. This computes the same mathematical result while using a linear solver directly.

from scipy.linalg import solve

A = np.array([[2.0, 1.0],
              [1.0, 1.0]])
b = np.array([1.0, 0.0])

result = b.copy()
for _ in range(3):
    result = solve(A, result)

assert np.allclose(result, matrix_power(A, -3) @ b)

Choosing matrix_power or repeated multiplication

For one requested exponent, matrix_power(A, n) is usually preferable to a loop that performs n multiplications. Exponentiation by squaring needs only O(log n) matrix multiplications, whereas repeated multiplication needs O(n). For small exponents, the difference may be insignificant; a direct loop can still be useful when it makes the surrounding calculation easier to read.

from scipy.linalg import matrix_power

A = np.array([[1.0, 1.0],
              [0.0, 1.0]])

power = np.eye(A.shape[0])
for _ in range(5):
    power = power @ A

assert np.allclose(power, matrix_power(A, 5))

The choice changes when the computation needs every intermediate power. A loop can reuse the previous result to produce A, A², through Aⁿ with one multiplication per step. Calling matrix_power separately for every exponent repeats work; for example, computing all powers independently costs O(n log n) matrix multiplications rather than O(n).

powers = [np.eye(A.shape[0])]
for _ in range(8):
    powers.append(powers[-1] @ A)

A8 = powers[8]
A8_direct = matrix_power(A, 8)

assert np.allclose(A8, A8_direct)

If the goal is to apply successive powers to a vector, keep the calculation in vector form instead of constructing each matrix power. A matrix-vector product typically costs less than a matrix-matrix product, and the loop produces each successive state directly.

x = np.array([1.0, 0.0])
states = [x]

for _ in range(8):
    x = A @ x
    states.append(x)

x8 = states[8]
x8_from_power = matrix_power(A, 8) @ states[0]

assert np.allclose(x8, x8_from_power)

For dense matrices, the matrix-matrix products used by matrix_power can be expensive even when the exponent is large. If a problem only requires Aⁿx, compare the cost of repeated matrix-vector products with the cost of forming Aⁿ and multiplying once. The best choice depends on the matrix size, exponent, and number of vectors to which the same power will be applied.

Both approaches use floating-point arithmetic, and their different multiplication orders can yield different rounding errors. When results are sensitive to those errors, test with representative inputs and compare using tolerances appropriate to the calculation.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *