# NumPy norm()

A norm is a mathematical concept that measures the size or length of a mathematical object, such as a matrix.

### Example

The `numpy.linalg.norm()` function computes the norm of a given matrix based on the specified order.

``````import numpy as np

# create a matrix
matrix1 = np.array([[1, 2], [3, 4]])

# compute norm of the matrix
norm = np.linalg.norm(matrix1)

print(norm)

# Output: 5.477225575051661``````

## norm() Syntax

The syntax of `norm()` is:

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

## norm() Arguments

The `norm()` method takes the following arguments:

• `matrix` - the input matrix for which the norm is computed
• `ord` (optional) - specify the order of the norm
• `axis` (optional) - specifies the axis or axes along which the norm is computed
• `keepdims` (optional) - determines whether the dimensions of the output are reduced or not

## norm() Return Value

The `norm()` method returns the computed norm of the input matrix as a scalar value.

## Example 1: Calculate the Frobenius norm of a matrix

The Frobenius norm, also known as the Euclidean norm, is a specific norm used to measure the size or magnitude of a matrix.

``````import numpy as np

# create a matrix
matrix1 = np.array([[11, 22], [31, 28]])

# compute the norm of the matrix using numpy.linalg.norm()
norm = np.linalg.norm(matrix1)

print(norm)``````

Output

`48.47679857416329`

Here, `np.linalg.norm()` calculates the Frobenius norm of matrix1, which is the square root of the sum of the squared absolute values of its elements.

Note: By default, the `numpy.linalg.norm()` function computes the Frobenius norm for matrices.

## Example 2: Compute L1 norm along a specific axis

The L1 norm is a measure of distance or magnitude in vector spaces. For a matrix, the L1 norm is calculated as the sum of the absolute values of its elements.

``````import numpy as np

# create a matrix
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# compute L1 norm along the rows (axis=0)
row_norm = np.linalg.norm(matrix1, ord=1, axis=0)

# compute L1 norm along the columns (axis=1)
col_norm = np.linalg.norm(matrix1, ord=1, axis=1)

print("L1 norm along rows: ", row_norm)
print("L1 norm along columns: ", col_norm)``````

Output

```L1 norm along rows:  [12. 15. 18.]
L1 norm along columns:  [ 6. 15. 24.]
```

Here, the L2 norm along each row is calculated by taking the square root of the sum of the squared absolute values of the elements in each row.

And, L1 norm along each column is obtained by summing the absolute values of the elements in each column.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

• Interactive Courses
• Certificates
• AI Help
• 2000+ Challenges