w3resource

Compute the Frobenius norm of a 3x3 random array using NumPy

NumPy: Advanced Exercise-24 with Solution

Write a NumPy program to create a 3x3 array with random values and compute the Frobenius norm of the matrix.

Sample Solution:

Python Code:

# Importing the necessary NumPy library
import numpy as np

# Create a 3x3 array with random values
array = np.random.rand(3, 3)

# Compute the Frobenius norm of the matrix
frobenius_norm = np.linalg.norm(array, 'fro')

# Printing the original array and its Frobenius norm
print("3x3 Array:\n", array)
print("Frobenius Norm of the array:\n", frobenius_norm)

Output:

3x3 Array:
 [[0.25748026 0.5277958  0.43826955]
 [0.01836537 0.417873   0.87132102]
 [0.92522201 0.07203685 0.14956437]]
Frobenius Norm of the array:
 1.5345014516959405

Explanation:

  • Import NumPy library: This step imports the NumPy library, which is essential for numerical operations.
  • Create a 3x3 array: We use np.random.rand(3, 3) to generate a 3x3 matrix with random values between 0 and 1.
  • Compute the Frobenius norm of the matrix: The np.linalg.norm function with the 'fro' argument calculates the Frobenius norm of the matrix, which is the square root of the sum of the absolute squares of its elements.
  • Print results: This step prints the original 3x3 array and its Frobenius norm.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Generate 6x6 array and compute Matrix rank with NumPy.
Next: Creating a 5x5 array with random values and finding row maximum Indices using NumPy.

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.