What is the numpy.linalg.matrix_power() Method

Numpy.linalg.matrix_power() method is “used to raise a square matrix to an integer power n.”

Syntax

numpy.linalg.matrix_power(M, n)

Parameters

The matrix_power() method takes two parameters:

  • M: This is the square matrix on which we want to operate.
  • n: This is the power value of the matrix.

Return Value

The method returns an integer after calculating the power.

Example 1: How to Use numpy.linalg.matrix_power() method

# Program when the value of N is greater than 0
from numpy import linalg as LA
import numpy as np

arr1 = np.array([[1, 2, 3], [3, 2, 4], [1, 0, 1]])
print("The array is:\n", arr1)

# When n=2
print("Matrix Power is:\n", LA.matrix_power(arr1, 2))

arr2 = np.array([[1, 2], [2, 1]])
print("The array is:\n", arr2)

# When n=1
print("Matrix Power is:\n", LA.matrix_power(arr2, 1))

Output

The array is:
 [[1 2 3]
 [3 2 4]
 [1 0 1]]
Matrix Power is:
 [[10 6 14]
 [13 10 21]
 [ 2 2 4]]
The array is:
 [[1 2]
 [2 1]]
Matrix Power is:
 [[1 2]
 [2 1]]

Example 2: Program when the value of N is 0 or less than 0.

# Program when the value of N is greater than 0
from numpy import linalg as LA
import numpy as np

arr1 = np.array([[1, 2, 3], [3, 2, 4], [1, 0, 1]])
print("The array is:\n", arr1)

# When n=0
print("Matrix Power is:\n", LA.matrix_power(arr1, 0))

arr2 = np.array([[1, 2], [2, 1]])
print("The array is:\n", arr2)

# When n=-2
print("Matrix Power is:\n", LA.matrix_power(arr2, -2))

Output

The array is:
 [[1 2 3]
 [3 2 4]
 [1 0 1]]
Matrix Power is:
 [[1 0 0]
 [0 1 0]
 [0 0 1]]
The array is:
 [[1 2]
 [2 1]]
Matrix Power is:
 [[ 0.55555556 -0.44444444]
 [-0.44444444 0.55555556]]

Example 3: numpy.linalg.matrix_power with positive power

import numpy as np

# Create a 2x2 matrix
matrix = np.array([[1, 2], [3, 4]])

# Raise the matrix to the power of 2
result = np.linalg.matrix_power(matrix, 2)

print(result)

Output

[[ 7 10]
 [15 22]]

Example 4: numpy.linalg.power() with negative power

import numpy as np

matrix = [[11, 19], [21, 46]]

mat_power = np.linalg.matrix_power(matrix, -2)

print("Matrix = \n", matrix, "\nMatrix power -2 = \n", mat_power)

Output

Matrix =
[[11, 19], [21, 46]]

Matrix power -2 =
[[ 0.21966984 -0.09459341]
[-0.10455062 0.04541881]]

That is it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.