Wednesday, December 25, 2024
Google search engine
HomeLanguagesFind a matrix or vector norm using NumPy

Find a matrix or vector norm using NumPy

To find a matrix or vector norm we use function numpy.linalg.norm() of Python library Numpy. This function returns one of the seven matrix norms or one of the infinite vector norms depending upon the value of its parameters.
 

Syntax: numpy.linalg.norm(x, ord=None, axis=None)
Parameters: 
x: input 
ord: order of norm 
axis: None, returns either a vector or a matrix norm and if it is an integer value, it specifies the axis of x along which the vector norm will be computed 
 

Example 1: 
 

Python3




# import library
import numpy as np
 
# initialize vector
vec = np.arange(10)
 
# compute norm of vector
vec_norm = np.linalg.norm(vec)
 
print("Vector norm:")
print(vec_norm)


Output:
 

Vector norm:
16.881943016134134

The above code computes the vector norm of a vector of dimension (1, 10)
Example 2: 
 

Python3




# import library
import numpy as np
 
# initialize matrix
mat = np.array([[ 1, 2, 3],
               [4, 5, 6]])
 
# compute norm of matrix
mat_norm = np.linalg.norm(mat)
 
print("Matrix norm:")
print(mat_norm)


Output:
 

Matrix norm:
9.539392014169456

Here, we get the matrix norm for a matrix of dimension (2, 3)
Example 3: 
To compute matrix norm along a particular axis – 
 

Python3




# import library
import numpy as np
 
 
mat = np.array([[ 1, 2, 3],
               [4, 5, 6]])
 
# compute matrix num along axis
mat_norm = np.linalg.norm(mat, axis = 1)
 
print("Matrix norm along particular axis :")
print(mat_norm)


Output:
 

Matrix norm along particular axis :
[3.74165739 8.77496439]

This code generates a matrix norm and the output is also a matrix of shape (1, 2)
Example 4: 
 

Python3




# import library
import numpy as np
 
# initialize vector
vec = np.arange(9)
 
# convert vector into matrix
mat = vec.reshape((3, 3))
 
# compute norm of vector
vec_norm = np.linalg.norm(vec)
 
print("Vector norm:")
print(vec_norm)
 
# computer norm of matrix
mat_norm = np.linalg.norm(mat)
 
print("Matrix norm:")
print(mat_norm)


Output:
 

Vector norm:
14.2828568570857
Matrix norm:
14.2828568570857

From the above output, it is clear if we convert a vector into a matrix, or if both have same elements then their norm will be equal too.
 

RELATED ARTICLES

Most Popular

Recent Comments