NumPy: Create an array which looks like below array
Create Zero/One Array Template
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics