w3resource

NumPy: Create an array which looks like below array

NumPy: Array Object Exercise-47 with Solution

Write a NumPy program to create an array like the one below.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Generating a lower-triangular matrix of size 4x3 with ones on and below the main diagonal shifted by -1
x = np.tri(4, 3, -1)

# Printing the generated matrix
print(x) 

Sample Output:

[[ 0.  0.  0.]                                                         
 [ 1.  0.  0.]                                                         
 [ 1.  1.  0.]                                                         
 [ 1.  1.  1.]]

Explanation:

The above code demonstrates how to create a NumPy array using the np.tri() function.

x = np.tri(4, 3, -1): The current line creates a NumPy array x using the np.tri() function. The function takes three arguments: the number of rows (4), the number of columns (3), and the diagonal below which the elements should be set to 1 (-1). The array is created with ones at and below the specified diagonal and zeros elsewhere.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 1-D array of 20 element spaced evenly on a log scale between 2. and 5., exclusive.
Next: Write a NumPy program to create an array which looks like below array.

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-exercise-47.php