Skip to content
Related Articles

Related Articles

Raise a square matrix to the power n in Linear Algebra using NumPy in Python

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Jun, 2022
View Discussion
Improve Article
Save Article

In this article, we will discuss how to raise a square matrix to the power n in the Linear Algebra in Python.

The numpy.linalg.matrix_power() method is used to raise a square matrix to the power n. It will take two parameters, The 1st parameter is an input matrix that is created using a NumPy array and the  2nd parameter is the exponent n, which refers to the power that can be zero or non-zero integers.

Syntax: numpy.linalg.matrix_power(input_numpy_matrix,n)

Parameters:

  • input_numpy_matrix is the matrix.
  • n refers to the integer value thar raise the matrix.

Return: It will return matrix that is raised to power n

Example 1

In this example, we are creating a 2D array (matrix) with 2 rows and 2 columns and returning the matrix raised to 0th power, matrix raised to 4th power, and matrix raised to 5th power.

Python3




# import numpy and matrix_power
import numpy
from numpy.linalg import matrix_power
  
# Create a 2D array
input_array = numpy.array([[3, 4], [4, 5]])
  
# Display  array
print(input_array)
  
# Using  numpy.linalg.matrix_power() to 
# return raise 0 th power of matrix
print(matrix_power(input_array, 0))
  
print()
  
# Using  numpy.linalg.matrix_power() to 
# return raise 4 th power of matrix
print(matrix_power(input_array, 4))
  
print()
  
# Using  numpy.linalg.matrix_power() to
# return raise 5 th power of matrix
print(matrix_power(input_array, 5))


Output:

[[3 4]
 [4 5]]
[[1 0]
 [0 1]]

[[1649 2112]
 [2112 2705]]

[[13395 17156]
 [17156 21973]]

Example 2

In this example, we are creating a 2D  array (matrix) with 4 rows and 4 columns and returning the matrix raised to 0th power, matrix raised to 4th power, and matrix raised to 5th power.

Python3




# import numpy and matrix_power
import numpy
from numpy.linalg import matrix_power
  
# Create a 2D array
input_array = numpy.array(
    [[3, 4, 3, 4], [4, 5, 2, 2], [1, 1, 0, -2], 
     [-4, 5, 4, -1]])
  
# Display  array
print(input_array)
  
# Using  numpy.linalg.matrix_power() to 
# return raise 0 th power of matrix
print(matrix_power(input_array, 0))
  
print()
  
# Using  numpy.linalg.matrix_power() to
# return raise 4 th power of matrix
print(matrix_power(input_array, 4))
  
print()
  
# Using  numpy.linalg.matrix_power() to
# return raise 5 th power of matrix
print(matrix_power(input_array, 5))


Output:

[[ 3  4  3  4]
 [ 4  5  2  2]
 [ 1  1  0 -2]
 [-4  5  4 -1]]
[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]

[[2229 3622 1887 1354]
 [2460 4369 2238 1300]
 [ 237  839  426    2]
 [ 102 1206  864  441]]

[[17646 35683 19347 11032]
 [21894 40423 21318 12802]
 [ 4485  5579  2397  1772]
 [ 4230  9507  4482   651]]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!