Numpy | Linear Algebra (original) (raw)

Last Updated : 20 May, 2026

NumPy provides a linalg module for performing linear algebra operations on arrays and matrices. It includes functions for finding matrix rank, determinant, trace, eigenvalues, matrix inversion, matrix exponentiation and solving linear equations.

Python `

import numpy as np

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

print("Rank of A:", np.linalg.matrix_rank(A)) print("Trace of A:", np.trace(A)) print("Determinant of A:", np.linalg.det(A)) print("Inverse of A:\n", np.linalg.inv(A)) print("Matrix A raised to power 3:\n", np.linalg.matrix_power(A, 3))

`

**Output:

Rank of A: 3
Trace of A: 11
Determinant of A: -306.0
Inverse of A:
[[ 0.17647059 -0.00326797 -0.02287582]
[ 0.05882353 -0.13071895 0.08496732]
[-0.11764706 0.1503268 0.05228758]]
Matrix A raised to power 3:
[[336 162 228]
[406 162 469]
[698 702 905]]

Matrix and Vector Products

**1. Using dot() function: returns the dot product of two arrays. It works with both 1D (vectors) and 2D (matrices). When used on 2D arrays, it performs matrix multiplication.

For N dimensions it is a sum product over the last axis of a and the second-to-last of b:

dot(a, b)[i, j, k, m] = sum(a[i, j, :] * b[k, :, m])

Python `

import numpy as np

prod = np.dot(5, 4) print("Dot Product of scalar values:", prod)

a = 2 + 3j b = 4 + 5j res = np.dot(a, b) print("Dot Product:", res)

`

Output

Dot Product of scalar values: 20 Dot Product: (-7+22j)

**Explanation:

a = 2 + 3j
b = 4 + 5j

Now, dot product
= 2(4 + 5j) + 3j(4 - 5j)
= 8 + 10j + 12j - 15
= -7 + 22j

**2. Using vdot() function: returns the dot product, but it takes the complex conjugate of the first argument before multiplying. This makes it useful for complex-valued arrays.

Python `

import numpy as np

a = 2 + 3j b = 4 + 5j res = np.vdot(a, b) print("Dot Product:",res)

`

Output

Dot Product: (23-2j)

**Explanation:

a = 2 + 3j
b = 4 + 5j

As per method, take conjugate of a i.e. 2 - 3j
Now, dot product = 2(4 - 5j) + 3j(4 - 5j)
= 8 - 10j + 12j + 15
= 23 - 2j

Common Matrix and Vector Product Functions

Following table lists commonly used NumPy functions for performing various types of matrix and vector multiplications:

FUNCTION DESCRIPTION
matmul() Matrix product of two arrays.
inner() Inner product of two arrays.
outer() Compute the outer product of two vectors.
linalg.multi_dot() Compute the dot product of two or more arrays in a single function call, while automatically selecting the fastest evaluation order.
tensordot() Compute tensor dot product along specified axes for arrays >= 1-D.
einsum() Evaluates the Einstein summation convention on the operands.
einsum_path() Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays.
linalg.matrix_power() Raise a square matrix to the (integer) power n.
kron() Kronecker product of two arrays.

Solving Equations and Inverting Matrices

**1. Using linalg.solve() function: It is used to find the exact solution of a linear system of equations of the form Ax = b, where:

import numpy as np

a = np.array([[1, 2], [3, 4]]) b = np.array([8, 18]) print(("Solution of linear equations:", np.linalg.solve(a, b)))

`

Output

('Solution of linear equations:', array([2., 3.]))

**2. Using linalg.lstsq() function: finds the best possible fit minimizing the difference between When a system doesn’t have an exact solution (for example, when it’s overdetermined), predicted and actual values.

Python `

import numpy as np import matplotlib.pyplot as plt

x = np.arange(0, 9) A = np.array([x, np.ones(9)]) y = [19, 20, 20.5, 21.5, 22, 23, 23, 25.5, 24] w = np.linalg.lstsq(A.T, y)[0]

line = w[0]*x + w[1] plt.plot(x, line, 'r-') plt.plot(x, y, 'o') plt.show()

`

**Output

4

Common Functions for Solving and Inverting Matrices

Below are some of the most useful functions to solve, invert or compute pseudoinverses of matrices:

FUNCTION DESCRIPTION
numpy.linalg.tensorsolve() Solve the tensor equation a x = b for x.
numpy.linalg.inv() Compute the (multiplicative) inverse of a matrix.
numpy.linalg.pinv() Compute the (Moore-Penrose) pseudo-inverse of a matrix.
numpy.linalg.tensorinv() Compute the ‘inverse’ of an N-dimensional array.

Special Functions in Linear Algebra

**1. Finding the Determinant - numpy.linalg.det(): The determinant is a number that can be calculated from a square matrix. It helps determine whether a matrix is invertible and is often used in solving systems of linear equations.

Python `

import numpy as np

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

print(("Determinant of A:", np.linalg.det(A)))

`

Output

('Determinant of A:', np.float64(-306.0))

**2. Finding the Trace - numpy.trace(): The trace of a matrix is the sum of its diagonal elements. It’s often used in linear algebra and statistics.

Python `

import numpy as np

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

print("Trace of A:", np.trace(A))

`

Common Special Functions

Here’s a list of other specialized linear algebra functions available in NumPy:

FUNCTION DESCRIPTION
numpy.linalg.norm() Matrix or vector norm.
numpy.linalg.cond() Compute the condition number of a matrix.
numpy.linalg.matrix_rank() Return matrix rank of array using SVD method
numpy.linalg.cholesky() Cholesky decomposition.
numpy.linalg.qr() Compute the qr factorization of a matrix.
numpy.linalg.svd() Singular Value Decomposition.

Matrix Eigenvalues Functions

NumPy provides functions in its linalg (Linear Algebra) module to calculate eigenvalues and eigenvectors of matrices.

**1. Using linalg.eigh() function: It is used for Hermitian (complex symmetric) or real symmetric matrices. It returns two values:

import numpy as np from numpy import linalg as geek

a = np.array([[1, -2j], [2j, 5]]) print("Array is:\n", a)

c, d = geek.eigh(a) print("Eigenvalues are:", c) print("Eigenvectors are:\n", d)

`

**Output

Array is:
[[ 1.+0.j -0.-2.j]
[ 0.+2.j 5.+0.j]]
Eigenvalues are: [0.17157288 5.82842712]
Eigenvectors are:
[[-0.92387953+0.j -0.38268343+0.j ]
[ 0. +0.38268343j 0. -0.92387953j]]

**2. Using linalg.eig() function: It is used for general square matrices (not necessarily symmetric). It also returns both eigenvalues and eigenvectors.

Python `

import numpy as np from numpy import linalg as geek

a = np.diag((1, 2, 3)) print("Array is:\n", a)

c, d = geek.eig(a) print("Eigenvalues are:", c) print("Eigenvectors are:\n", d)

`

Output

Array is: [[1 0 0] [0 2 0] [0 0 3]] Eigenvalues are: [1. 2. 3.] Eigenvectors are: [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]

Common Eigenvalue Functions

This table summarizes various functions related to eigenvalue and eigenvector computations:

FUNCTION DESCRIPTION
linalg.eigvals() Compute the eigenvalues of a general matrix.
linalg.eigvalsh(a[, UPLO]) Compute the eigenvalues of a complex Hermitian or real symmetric matrix.