w3resource

NumPy: Find a matrix or vector norm

NumPy: Linear Algebra Exercise-10 with Solution

Write a NumPy program to find a matrix or vector norm.

Notes on Vector and Matrix Norms from here

Sample Solution :

Python Code :

# Import the NumPy library and alias it as 'np'
import numpy as np

# Create a NumPy array 'v' containing elements from 0 to 6
v = np.arange(7)

# Calculate the L2 norm (Euclidean norm) of the vector 'v'
result = np.linalg.norm(v)

# Display the computed L2 norm of the vector 'v'
print("Vector norm:")
print(result)

# Create a 2x2 matrix 'm' using the np.matrix function
m = np.matrix('1, 2; 3, 4') 

# Calculate the Frobenius norm of the matrix 'm'
result1 = np.linalg.norm(m)

# Display the computed Frobenius norm of the matrix 'm'
print("Matrix norm:")
print(result1)

Sample Output:

Vector norm:
9.53939201417
Matrix norm:
5.47722557505

Explanation:

v = np.arange(7): This line creates a 1D NumPy array v with elements ranging from 0 to 6.

result = np.linalg.norm(v): This line computes the 2-norm (also known as the Euclidean norm) of the vector v. The 2-norm is the square root of the sum of the squared elements of the vector. In this case, the result is approximately 11.832159566199232.

m = np.matrix('1, 2; 3, 4'): This line creates a 2x2 matrix m with the specified elements.

result1 = np.linalg.norm(m): This line computes the Frobenius norm of the matrix m. The Frobenius norm is the square root of the sum of the squared elements of the matrix. In this case, the result is approximately 5.477225575051661.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute the condition number of a given matrix.
Next: Write a NumPy program to compute the determinant of an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.