w3resource

NumPy: Create a 2-D array whose diagonal equals


2D Array with Custom Diagonal Values

Write a NumPy program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.

Pictorial Presentation:

Python NumPy: Create a 2-D array whose diagonal equals

Sample Solution:

Python Code:

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

# Creating a 2-D array with the specified diagonal elements and zeros elsewhere
x = np.diagflat([4, 5, 6, 8])

# Printing the resulting 2-D array
print(x) 

Sample Output:

[[4 0 0 0]                                                             
 [0 5 0 0]                                                             
 [0 0 6 0]                                                             
 [0 0 0 8]]

Explanation:

This code demonstrates how to create a diagonal matrix using the np.diagflat() function in NumPy.

x = np.diagflat([4, 5, 6, 8]): The current line creates a diagonal matrix ‘x’ using the np.diagflat() function. The function takes one argument, which is a list or array-like object containing the values to be placed on the diagonal of the resulting matrix.

print(x): The current line prints the diagonal matrix ‘x’.

Python-Numpy Code Editor: