w3resource

Advanced NumPy Exercises - Normalize a 5x5 array row-wise with random values

NumPy: Advanced Exercise-6 with Solution

Write a NumPy program to create a 5x5 array with random values and normalize it row-wise.

Sample Solution:

Python Code:

import numpy as np
# create 5x5 array with random values
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
# normalize row-wise
norm_arr = nums / np.linalg.norm(nums, axis=1, keepdims=True)
print("\nNormalize Array row-wise:")
print(norm_arr)

Output:

Original array elements:
[[0.96984536 0.03044869 0.01721181 0.89185135 0.97561925]
 [0.63986486 0.99058455 0.67101686 0.93148062 0.4123554 ]
 [0.58921689 0.79738557 0.59987027 0.14101544 0.68292227]
 [0.74824255 0.66308133 0.34566079 0.18339684 0.92431556]
 [0.73276253 0.13083497 0.96101991 0.57190127 0.66658679]]

Normalize Array row-wise:
[[0.59142903 0.01856816 0.01049607 0.54386689 0.59495005]
 [0.37713294 0.58384526 0.39549376 0.54900971 0.24304008]
 [0.43566728 0.58958731 0.44354439 0.10426689 0.50495308]
 [0.52816143 0.46804874 0.24399134 0.12945419 0.65244595]
 [0.48861401 0.08724218 0.64081852 0.38134998 0.44448731]]

Explanation:

In the above code -

nums = np.random.rand(5, 5): This line creates a 5x5 NumPy array with random values between 0 and 1.

np.linalg.norm(nums, axis=1, keepdims=True): This calculates the Euclidean norm of each row in nums. The axis=1 argument specifies that the norm should be calculated along the rows, and keepdims=True ensures that the result is a column vector with the same number of dimensions as nums.

norm_arr = nums / np.linalg.norm(nums, axis=1, keepdims=True): This line divides each element in nums by the corresponding row norm, effectively normalizing the rows of nums. The resulting array norm_arr has the same shape as nums, but with each row normalized to unit length.

Python-Numpy Code Editor:

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

Previous: Subtract the mean of each column from each element of a 3x3 array.
Next: Normalize a 5x5 array column-wise with random values.

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://www.w3resource.com/python-exercises/numpy/advanced-numpy-exercise-6.php