Return the Norm of the vector over axis 1 in Linear Algebra in Python

PythonNumpyServer Side ProgrammingProgramming

To return the Norm of the matrix or vector in Linear Algebra, use the LA.norm() method in Python Numpy. The 1st parameter, x is an input array. If axis is None, x must be 1-D or 2-D, unless ord is None. If both axis and ord are None, the 2-norm of x.ravel will be returned. The 2nd parameter, ord is the order of the norm. The inf means numpy’s inf object. The default is None.

The 3rd parameter axis, if an integer, specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The default is None.

The 4th parameter, keepdims, if set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original x.

Steps

At first, import the required library −

import numpy as np
from numpy import linalg as LA

Create an array −

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

Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)

Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the Shape −

print("\nShape of our Array object...\n",arr.shape)

To return the Norm of the matrix or vector in Linear Algebra, use the LA.norm() method in Python Numpy −

print("\nResult...\n",LA.norm(arr, axis = 1))

Example

import numpy as np
from numpy import linalg as LA

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

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To return the Norm of the matrix or vector in Linear Algebra, use the LA.norm() method in Python Numpy
print("\nResult...\n",LA.norm(arr, axis = 1))

Output

Our Array...
   [[ 1 2 3]
   [-1 1 4]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Shape of our Array object...
(2, 3)

Result...
   [3.74165739 4.24264069]
raja
Updated on 09-Mar-2022 05:19:04

Advertisements