Free cookie consent management tool by TermsFeed Finding vector norm using NumPy | Pythontic.com

Finding vector norm using NumPy

Overview:

  • Vector Norm is a measure of the length of a vector or the magnitude of the vector.

  • Different types of vector norms measure the vector in different ways, but all of them give a number to convey the magnitude of the vector using a function.

  • So, the norm of a vector is a function that assigns non-negative real numbers to vectors which satisfy the following properties:

    • ||x|| > 0 when x ^= 0 and ||X|| = 0 when x = 0

    • ||k x|| = ||k|| ||x||

    • ||x+y|| <= ||x|| ||y||

Types of Vector Norms:

Euclidean norm: Sum of the squares of the components of the vector.

||x||2 = (Σxi)1/2, where i = 1 to n

Infinity norm: The maximum absolute value of the components of the vector.

||x|| = max|xi|, where i = 1 to n

1-norm: The sum of the absolute value of the components of the vector.

||x||1 = (Σ|xi|), where i = 1 to n

Calculating the norm of a vector using NumPy:

  • The NumPy function vector_norm() from the linalg module computes the vector norm for one are more vectors.

  • The type of norm can be specified using the ord parameter of the vector_norm() function.

Example:

# Example Python program that computes the vector norms of the
# a) Flattened array
# b) Column vetcors
# c) Row vectors
# from a 3x3 matrix
import numpy

# Create a square matrix
elements     = numpy.arange(1, 18, 2)
matrix      = elements.reshape(3, 3)
print("Input vector(s):")
print(matrix)

# Since no axis is specified all the elements
# of the 3x3 matrix is considered as a flattened array.
# Square root of sum of all the elements
vectorNorm = numpy.linalg.vector_norm(matrix)
print("Vector norm (Each element is a component of the vector):")
print(vectorNorm)

# Vector norms for three column vectors are computed
vectorNorm = numpy.linalg.vector_norm(matrix, axis=0)
print("Vector norms of the column vectors:")
print(vectorNorm)

# Vector norms for three row vectors are computed
vectorNorm = numpy.linalg.vector_norm(matrix, axis=1)
print("Vector norms of the row vectors:")
print(vectorNorm)

Output:

Input vector(s):
[[ 1  3  5]
 [ 7  9 11]
 [13 15 17]]
Vector norm (Each element is a component of the vector):
31.12876483254676
Vector norms of the column vectors:
[14.79864859 17.74823935 20.85665361]
Vector norms of the row vectors:
[ 5.91607978 15.84297952 26.13426869]

 


Copyright 2025 © pythontic.com