w3resource

NumPy: Normalize a 3x3 random matrix

NumPy: Random Exercise-7 with Solution

Write a NumPy program to normalize a 3x3 random matrix.

Sample Solution:

Python Code :

# Importing the NumPy library as np
import numpy as np

# Generating a 3x3 array of random numbers between 0 and 1 using np.random.random()
x = np.random.random((3, 3))

# Printing the original array 'x'
print("Original Array:")
print(x)

# Finding the maximum and minimum values in array 'x' using x.max() and x.min()
xmax, xmin = x.max(), x.min()

# Normalizing the array 'x' using min-max scaling: (x - xmin) / (xmax - xmin)
x = (x - xmin) / (xmax - xmin)

# Printing the array 'x' after normalization
print("After normalization:")
print(x) 

Sample Output:

Original Array:                                                        
[[ 0.89372503  0.99865458  0.77120044]                                 
 [ 0.67632984  0.99990084  0.64110391]                                 
 [ 0.34845794  0.66557903  0.29031742]]                                
After normalization:                                                   
[[ 0.85036881  0.99824367  0.67769765]                                 
 [ 0.54399864  1.          0.49435553]                                 
 [ 0.08193614  0.52884777  0.        ]]

Explanation:

x = np.random.random((3,3)): This line creates a 3x3 array x with random numbers between 0 and 1 using the np.random.random() function. The input tuple (3,3) specifies the output array shape.

xmax, xmin = x.max(), x.min(): This line finds the maximum and minimum values in the array x using the x.max() and x.min() methods, respectively. These values are stored in the variables xmax and xmin.

x = (x - xmin)/(xmax - xmin): This line normalizes the array x by rescaling its elements to the range [0, 1]. This is done by subtracting the minimum value xmin from all elements in the array and then dividing the result by the range (xmax - xmin). The normalized values are stored back into array x.

print(x): Finally print() function prints the normalized 3x3 array x.

Pictorial Presentation:

NumPy Random: Normalize a 3x3 random matrix.

Python-Numpy Code Editor:

Previous: Write a NumPy program to shuffle numbers between 0 and 10 (inclusive).
Next: Write a NumPy program to create a random vector of size 10 and sort it.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-random-exercise-7.php