SciPy - Matrix Creation & Basic Operations



SciPy offers many convenient functions for creating and manipulating matrices by extending the capabilities of NumPy. The scipy.linalg module in SciPy provides functions for creating and performing basic operations on matrices such as linear algebraic computations like solving systems of linear equations, finding determinants and performing matrix factorization.

It is similar to the NumPy library but SciPys linalg module extends NumPys capabilities with more advanced linear algebra tools.

In this chapter let's discuss in detail about the matrix creation and basic operations using scipy.linalg

Creating a Matrix in SciPy

Matrix creation in SciPy and NumPy involves using a variety of functions to initialize matrices with different values, structures and properties. Here are various ways to create matrices in SciPy which focus on common techniques, special matrices and properties −

To create matrices SciPy uses the same array creation techniques as NumPy with an additional focus on linear algebra functions. Here is the example of it −

import numpy as np
import scipy.linalg as la

# Creating a matrix (2x2)
A = np.array([[1, 2], [3, 4]])
print("The 2x2 matrix:",A)
# Creating a square matrix of zeros (3x3)
B = np.zeros((3, 3))
print("The 3x3 square matrix:,"B)
# Creating an identity matrix (4x4)
I = np.eye(4)
print("The 4X4 Identity matrix:,"I)
# Creating a random matrix
R = np.random.rand(3, 3)
print("The Random matrix:,"R)

Following is the output of creating the different type of matrices −

The 2x2 matrix: [[1 2]
 [3 4]]
The 3x3 square matrix: [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
The 4X4 Identity matrix: [[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
The Random matrix: [[0.93209861 0.44003913 0.94137284]
 [0.25650407 0.59441862 0.49890997]
 [0.65446923 0.38596346 0.92084365]]

Basic Matrix Operations in SciPy

scipy.linalg supports numerous matrix operations such as addition, subtraction, multiplication, transpose, etc. Some functions are more efficient than using basic NumPy operations.

Matrix Multiplication

Scipy does not have functions to perform the matrix multiplication, in such case we can use the numpy library np.matmul() function. Following is the example of performing the matrix multiplication using np.matmul() and @ decorator −

import numpy as np

# Define matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
import scipy.linalg as la

# Matrix multiplication
F = A @ B  # Using @ operator
G = np.matmul(A, B)  # Using np.matmul

print("Matrix Multiplication using @:\n", F)
print("Matrix Multiplication using np.matmul:\n", G)

Following is the output of matrix multiplication performed using @ and np.transpose()

Matrix Multiplication using @:
 [[19 22]
 [43 50]]
Matrix Multiplication using np.matmul:
 [[19 22]
 [43 50]]

Matrix Transpose in SciPy

Since scipy.linalg module doesnt provide a direct transpose function its common to use numpy.transpose() or the .T attribute for this operation. Both approaches are efficient and work well with scipy for other matrix operations if we need them. Following is the example of performing matrix transpose −

import numpy as np

A = np.array([[1, 2], [3, 4]])
A_transpose = A.T
print("Matrix transpose using .T",A_transpose)
transpose_matrix = np.transpose(A)
print("Matrix transpose using transpose()",transpose_matrix)

Following is the output of Performing matrix transpose using numpy −

Matrix transpose using .T [[1 3]
 [2 4]]
Matrix transpose using transpose() [[1 3]
 [2 4]]

Matrix Addition and Subtraction in SciPy

Matrix addition and subtraction are not directly available in scipy.linalg either as these are basic operations typically handled by numpy. However we can use scipy in combination with numpy to perform these operations. Below is the example which shows how to perform matrix addition and subtraction using numpy −

import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Matrix addition
C_add = A + B
print("Addition:\n", C_add)

# Matrix subtraction
C_subtract = A - B
print("Subtraction:\n", C_subtract)

Following is the output of Performing matrix addition and subtraction using numpy −

Addition:
 [[ 6  8]
 [10 12]]
Subtraction:
 [[-4 -4]
 [-4 -4]]

Element wise Matrix Multiplication in SciPy

Element-wise multiplication in Python can be easily done with numpy using either the * operator or numpy.multiply. While scipy.linalg does not provide a specific function for element-wise multiplication we can still use numpy alongside scipy. Here is the example of it −

import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

# Element-wise multiplication
C = A * B
print("Element-wise Multiplication using *:\n", C)
D = np.multiply(A, B)
print("Element-wise Multiplication using multiply():\n", D)

Following is the output of Performing matrix element wise multiplication −

Element-wise Multiplication using *:
 [[ 5 12]
 [21 32]]
Element-wise Multiplication using multiply():
 [[ 5 12]
 [21 32]]

Matrix Inversion in SciPy

Matrix inversion is the process of finding a matrix that, when multiplied by the original matrix, yields the identity matrix. In scipy.linalg matrix inversion can be done using the scipy.linalg.inv() function.

Following are the key points to be considered while performing inversion of the matrix −

  • scipy.linalg.inv(A) computes the inverse of matrix A.
  • The matrix must be square i.e., it has the same number of rows and columns and non-singular i.e., it must have a non-zero determinant.
  • After computing the inverse we can verify the result by multiplying the original matrix with its inverse which should yield the identity matrix.

Check for Singular Matrix

We can check the determinant using np.linalg.det(A) or scipy.linalg.det(A) to finrd whether the given matrix is singular or not. If the matrix is singular then it has a determinant of 0 and the inversion will fail and we will get an error or a warning. Here is the example which checks for the singular matrix −

import numpy as np
from scipy import linalg

# Define a square matrix
A = np.array([[1, 2], [3, 4]])

if linalg.det(A) == 0:
    print("Matrix is singular, so it doesn't have an inverse.")
else:
    A_inv = linalg.inv(A)
    print("Inverse of A:", A_inv)

Following is the output which checks whether the given matrix is singular or not −

Inverse of A: [[-2.   1. ]
 [ 1.5 -0.5]]

Here is the example which shows how we can perform matrix inversion using scipy.linalg.inv()

import numpy as np
from scipy import linalg

# Define a square matrix
A = np.array([[1, 2], [3, 4]])

# Compute the inverse using scipy.linalg.inv
A_inv = linalg.inv(A)

print("Matrix A:")
print(A)

print("\nInverse of A:")
print(A_inv)

# To verify the result, multiply the matrix with its inverse and check if it gives the identity matrix
identity_matrix = np.dot(A, A_inv)
print("\nA * A_inv (should be identity matrix):")
print(identity_matrix)

Following is the output of Performing matrix inversion using the scipy.linalg.inv() −

Inverse of A: [[-2.   1. ]
 [ 1.5 -0.5]]
PS D:\Tutorialspoint> python sample.py
Matrix A:
[[1 2]
 [3 4]]

Inverse of A:
[[-2.   1. ]
 [ 1.5 -0.5]]

A * A_inv (should be identity matrix):
[[1.0000000e+00 0.0000000e+00]
 [8.8817842e-16 1.0000000e+00]]

Matrix Determinant in SciPy

The determinant of a square matrix is a scalar value that provides significant information about the matrix. In linear algebra the determinant can be used to answer questions about the invertibility of a matrix among other things.

In this example to compute the determinant of a matrix we are using SciPy where we can use the function scipy.linalg.det()

import numpy as np
from scipy import linalg

# Define a square matrix
A = np.array([[1, 2], [3, 4]])

# Compute the determinant using scipy.linalg.det
det_A = linalg.det(A)

print("Matrix A:")
print(A)

print("\nDeterminant of A:")
print(det_A)

Following is the output of Performing matrix determinant using the scipy.linalg.det() −

Matrix A:
[[1 2]
 [3 4]]

Determinant of A:
-2.0
Advertisements