- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Raise a square matrix to the power n in Linear Algebra in Python
To raise a square matrix to the power n in Linear Algebra, use the numpy.linalg.matrix_power() in Python For positive integers n, the power is computed by repeated matrix squarings and matrix multiplications. If n == 0, the identity matrix of the same shape as M is returned. If n < 0, the inverse is computed and then raised to the abs(n).
The return value is the same shape and type as M; if the exponent is positive or zero then the type of the elements is the same as those of M. If the exponent is negative the elements are floating-point. The 1st parameter, a is a matrix to be “powered”. The 2nd parameter, n is the exponent that can be any integer or long integer, positive, negative, or zero.
Steps
At first, import the required libraries −
import numpy as np from numpy.linalg import matrix_power
Create a 2D array, matrix equivalent of the imaginary unit −
arr = np.array([[0, 1], [-1, 0]])
Display the array −
print("Our Array...\n",arr)
Check the Dimensions −
print("\nDimensions of our Array...\n",arr.ndim)
Get the Datatype −
print("\nDatatype of our Array object...\n",arr.dtype)
Get the Shape −
print("\nShape of our Array object...\n",arr.shape)
To raise a square matrix to the power n in Linear Algebra, use the numpy.linalg.matrix_power() in Python. For positive integers n, the power is computed by repeated matrix squarings and matrix multiplications. If n == 0, the identity matrix of the same shape as M is returned. If n < 0, the inverse is computed and then raised to the abs(n) −
print("\nResult...\n",matrix_power(arr, 0))
Example
import numpy as np from numpy.linalg import matrix_power # Create a 2D array, matrix equivalent of the imaginary unit arr = np.array([[0, 1], [-1, 0]]) # Display the array print("Our Array...\n",arr) # Check the Dimensions print("\nDimensions of our Array...\n",arr.ndim) # Get the Datatype print("\nDatatype of our Array object...\n",arr.dtype) # Get the Shape print("\nShape of our Array object...\n",arr.shape) # To raise a square matrix to the power n in Linear Algebra, use the numpy.linalg.matrix_power() in Python print("\nResult...\n",matrix_power(arr, 0))
Output
Our Array... [[ 0 1] [-1 0]] Dimensions of our Array... 2 Datatype of our Array object... int64 Shape of our Array object... (2, 2) Result... [[1 0] [0 1]]