w3resource

Extract the uper triangular part of a 4x4 random array using NumPy

NumPy: Advanced Exercise-21 with Solution

Write a NumPy program to create a 4x4 array with random values and extract the upper triangular part of the matrix.

This NumPy program generates a 4x4 array filled with random values and then extracts its upper triangular portion. The upper triangular part consists of the elements above the main diagonal.

Sample Solution:

Python Code:

# Importing the necessary NumPy library
import numpy as np

# Create a 4x4 array with random values
array = np.random.rand(4, 4)

# Extract the upper triangular part of the matrix
upper_triangular = np.triu(array)

# Printing the original array and its upper triangular part
print("4x4 Array:\n", array)
print("Upper Triangular Part of the Array:\n", upper_triangular)

Output:

4x4 Array:
 [[0.78182673 0.33487408 0.98131048 0.06329237]
 [0.62694284 0.21797308 0.11079666 0.9965996 ]
 [0.21949739 0.3833903  0.57100561 0.6176376 ]
 [0.39506617 0.83982428 0.90600992 0.82911216]]
Upper Triangular Part of the Array:
 [[0.78182673 0.33487408 0.98131048 0.06329237]
 [0.         0.21797308 0.11079666 0.9965996 ]
 [0.         0.         0.57100561 0.6176376 ]
 [0.         0.         0.         0.82911216]]

Explanation:

  • Import NumPy library: This step imports the NumPy library, which is essential for numerical operations.
  • Create a 4x4 array: We use np.random.rand(4, 4) to generate a 4x4 matrix with random values between 0 and 1.
  • Extract the upper triangular part of the matrix: The np.triu function extracts the upper triangular part of the matrix, setting elements below the main diagonal to zero.
  • Print results: This step prints the original 4x4 array and its upper triangular part.

Python-Numpy Code Editor:

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

Previous: Calculate the Trace of a 5x5 random array using NumPy.
Next: Extract the lower triangular part of a 4x4 Random array using NumPy.

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/advanced-numpy-exercise-21.php