Python Scipy Matrix + Examples

In this Python tutorial, we will learn about the “Scipy Matrix” where we will discuss how to perform a variety of different operations on matrices using Scipy. And we will also cover the following topics.

  • Python Scipy Matrices
  • Python Scipy Matrix Inverse
  • Scipy Matrix Exponential
  • Python Scipy Matrix Power
  • Scipy Matrix Transpose
  • Python Scipy Matrix Norm
  • Python Scipy Matrix To Array
  • Scipy Matrix Square Root

Python Scipy Matrix

The Python Scipy has two module scipy.linalg and scipy.sparse to perform different types of operations on matrices. But first, we need to know about “What is the matrix?” if you don’t know. A matrix is a two-dimensional array in which each data member has the same size.

For many mathematical and scientific tasks, matrices are essential data structures. Here we’ll use Python to generate a matrix and then perform operations on it.

A Python matrix is a 2-dimensional rectangular array containing data recorded in rows and columns in a customized two-dimensional rectangular array. Numbers, strings, equations, symbols, and other types of data can all be found in a matrix.

Read: Scipy Find Peaks – Useful Tutorial

Python Scipy Matrix Inverse

The Python SciPy module scipy.linalg contains a method inv() that calculates a matrix’s inverse.

The syntax is given below.

scipy.linalg.inv(a, check_finite=False, overwrite_a=True,)

Where parameters are:

  • a(array_data): Input the matrix that we want to be inverted.
  • overwrite_a(boolean): To overwrite a.
  • check_finite(boolean): To check if the provided matrix as input has finite numbers.

The method inv() returns the ainv (which is the inverse of a matrix) of type ndarray.

Let’s take an example by following the below steps:

Import the required libraries using the below code.

from scipy.linalg import inv
import numpy as np

Create a matrix and inverse it using the below code.

matrix = np.array([[8, 7], [4, 3]])
inv(matrix)
Scipy Matrix Inverse
Scipy Matrix Inverse

This is how to inverse the given matrix using the method scipy.linalg.inv() of Python Scipy.

Read: Scipy Normal Distribution

Scipy Matrix Exponential

The Python SciPy module scipy.linalg contains a method expm() that uses Pade approximation to compute the matrix exponential.

The syntax is given below.

scipy.linalg.expm(A)

Where parameter A accepts the matrix of the type array.

The method expm() returns exponential of matrix A of type ndarray.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy import linalg
import numpy as np

Create a matrix and compute the exponential of that matrix using the below code.

mat = np.array([[2.0, 1.0], [3.0, -1.0]])
linalg.expm(1j*mat)
Scipy Matrix Exponential
Scipy Matrix Exponential

This is how to compute the exponential of the given matrix using the method expm() of Python SciPy.

Read: Scipy Ndimage Rotate

Python Scipy Matrix Power

The Python SciPy has a method fractional_matrix_power() within module scipy.linalg to calculate a matrix’s fractional power.

The syntax is given below.

scipy.linalg.fractional_matrix_power(A, t)

Where parameters are:

  • A(array_data like N, N): Input the matrix to evaluate the fractional power.
  • t(float): To specify the fraction power for the matrix.

The method fractional_matrix_power() returns x(which is fractional power of matrix) of type ndarray.

Let’s take an example to calculate the fractional power of the matrix by following the below steps:

Import the required libraries using the below code.

from scipy import linalg
import numpy as np

Create a matrix and calculate the fractional power of that matrix using the below code.

matrix = np.array([[3.0, 1.0], [4.0, 1.0]])
linalg.fractional_matrix_power(matrix,1.5)
Scipy Matrix Power
Scipy Matrix Power

This is how to calculate the fractional power of the matrix using the method fractional_matrix_power() of Python SciPy.

Read: Scipy Signal – Helpful Tutorial

Python Scipy Matrix Transpose

The matrix can be transposed or reversed using the method transpose() that exists within the module scipy.sparse.csr_matrix of Python SciPy.

The syntax is given below,

csr_matrix.transpose(axes=None, copy=True)

Where parameters are:

  • axes(optional, None): This argument is only included in the signature for NumPy compatibility. Nothing but the default value should be passed in.
  • copy(boolean): When possible, whether or not self-aspects should be duplicated. Depending on what type of sparse matrix is employed, the extent to which characteristics are transferred varies.

The method transpose() returns the p( which is transposed matrix).

Read: Scipy Convolve

Python Scipy Matrix Norm

Python SciPy module scipy.linalg contains a method norm() that returns matrix norms.

The syntax is given below.

scipy.linalg.norm(a, axis=None, ord=None, check_finite=True,  keepdims=True)

Where parameters are:

  • a(array_data): Inputs array If ord isn’t None, the axis must be None and a must be 1-D or 2-D. If both axis and ord are None, the a.ravel 2-norm will be returned.
  • axis(2 tuple of int, int): If the axis is an integer, then it indicates the axis the vector norms should be computed along. If the axis is a two-tuple, two-dimensional matrices are held on axes that are specified, and the matrix norms of these matrices are calculated.
  • ord(int, inf): It is used to provide the norm order.
  • check_finite(boolean): To check if the provided matrix as input has finite numbers.
  • keepdims(boolean): if this is set to true, the axes which are normed over are left in the result as dimensions with size one.

The method norm() returns the norm of the given matrix.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy.linalg import norm
import numpy as np

Create an array of data as a matrix whose norm will be computed using the below code.

array_data = np.arange(12) - 4.0
array_data

Compute the norm of the above-created matrix or array of data using the below code.

norm(array_data)
Scipy Matrix Norm
Scipy Matrix Norm

This is how to compute the normalization of a given matrix using the method norm() of Python SciPy.

Read: Scipy Misc + Examples

Python Scipy Matrix To Array

The Python Scipy module scipy.sparse.csr_matrix contains a method toarray() to convert the given matrix into an array.

The syntax is given below.

csr_matrix.toarray(order=None, out=None)

where parameters are:

  • order: It is used to specify which orders to use like row-major(C) and column-major(F) for storing the multi-dimensional data. By default, it is specified as None means no order.
  • out: It is used to specify how to return the result as an array (NumPy.matrix) like an output buffer instead of creating a new array while returning the result.

Let’s take an example using the below steps:

Import the necessary libraries using the below code.

import numpy as np
from scipy.sparse import csr_matrix

Creating arrays using the below code.

array_data = np.array([0, 0, 2, 2, 1, 1, 4, 4, 5, 5, 1, 1, 2])

Creating csr matrix using the below code.

csr_mat = csr_matrix(array_data)

Convert the csr matrix to the NumPy array matrix by applying the method toarray() on the matrix csr_mat using the below code.

csr_mat.toarray()
Scipy Matrix To Array
Scipy Matrix To Array

This is how to convert the given matrix using the method toarray() of Python SciPy.

Read: Scipy Integrate + Examples

Scipy Matrix Square Root

The Python SciPy module scipy.linalg contains a method sqrtm() that calculates the square root of the given matrix.

The syntax is given below.

scipy.linalg.sqrtm(A, disp=False, blocksize=64)

Where parameters are:

  • A(array_data): Input the matrix to evaluate the square root.
  • dist(boolean): Rather than returning the estimated error, print a warning if the error in the result is predicted to be high.
  • bolcksize(integer): Use a blocked algorithm if the block size is not degenerate in relation to the input array size.

The method sqrtm returns the sqrtm( which is the square root of the matrix) of type ndarray.

Let’s understand with an example by following the below steps:

Import the required libraries using the below python code.

from scipy import linalg
import numpy as np

Create a matrix and calculate the square root of that matrix using the below code.

mat = np.array([[2.0, 1.0], [3.0, -1.0]])
linalg.sqrtm(mat)
Scipy Matrix Square root
Scipy Matrix Square root

This is how to compute the square root of the given matrix using the method sqrtm() of Python SciPy.

Also, take a look at some more Scipy tutorials.

So, in this tutorial, we have learned about the “Scipy Matrix” with the help of a variety of examples. Moreover, we also covered the following topics.

  • Python Scipy Matrix
  • Python Scipy Matrix Inverse
  • Scipy Matrix Exponential
  • Python Scipy Matrix Power
  • Scipy Matrix Transpose
  • Python Scipy Matrix Norm
  • Python Scipy Matrix To Array
  • Scipy Matrix Square Root