Return the Norm of the matrix or vector in Linear Algebra in Python

To return the norm of a matrix or vector in Linear Algebra, use the numpy.linalg.norm() method. The norm is a mathematical concept that measures the "size" or "length" of a vector or matrix.

Syntax

numpy.linalg.norm(x, ord=None, axis=None, keepdims=False)

Parameters

The function accepts the following parameters ?

  • x ? Input array. If axis is None, x must be 1-D or 2-D
  • ord ? Order of the norm (default: None for 2-norm)
  • axis ? Axis along which to compute the norm (default: None)
  • keepdims ? If True, keeps dimensions in the result (default: False)

Example 1: Basic Matrix Norm

Let's calculate the Frobenius norm (default) of a 2D matrix ?

import numpy as np
from numpy import linalg as LA

# Create a 2D array
arr = np.array([[1, 2, 3], [-1, 1, 4]])

print("Array:")
print(arr)
print("\nShape:", arr.shape)

# Calculate the norm (default is Frobenius norm)
result = LA.norm(arr)
print("\nFrobenius Norm:", result)
Array:
[[ 1  2  3]
 [-1  1  4]]

Shape: (2, 3)

Frobenius Norm: 5.656854249492381

Example 2: Different Types of Norms

You can specify different norm orders using the ord parameter ?

import numpy as np
from numpy import linalg as LA

arr = np.array([3, 4, 5])

print("Vector:", arr)
print("\n1-norm (sum of absolute values):", LA.norm(arr, ord=1))
print("2-norm (Euclidean norm):", LA.norm(arr, ord=2))
print("Infinity norm (max absolute value):", LA.norm(arr, ord=np.inf))
Vector: [3 4 5]

1-norm (sum of absolute values): 12.0
2-norm (Euclidean norm): 7.0710678118654755
Infinity norm (max absolute value): 5.0

Example 3: Norm Along Specific Axis

Calculate norms along specific axes of a matrix ?

import numpy as np
from numpy import linalg as LA

arr = np.array([[1, 2, 3], [4, 5, 6]])

print("Matrix:")
print(arr)

# Norm along axis 0 (columns)
print("\nNorm along axis 0 (each column):", LA.norm(arr, axis=0))

# Norm along axis 1 (rows) 
print("Norm along axis 1 (each row):", LA.norm(arr, axis=1))
Matrix:
[[1 2 3]
 [4 5 6]]

Norm along axis 0 (each column): [4.12310563 5.38516481 6.70820393]
Norm along axis 1 (each row): [3.74165739 8.77496439]

Common Norm Types

Norm Type ord Parameter Description
1-norm 1 Sum of absolute values
2-norm (Euclidean) 2 or None Square root of sum of squares
Infinity norm np.inf Maximum absolute value
Frobenius norm 'fro' Matrix norm (default for 2D arrays)

Conclusion

The numpy.linalg.norm() function provides a versatile way to calculate various norms of vectors and matrices. Use different ord values for specific norm types and the axis parameter to compute norms along specific dimensions.

Updated on: 2026-03-26T19:15:27+05:30

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements