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’.


For more Practice: Solve these Related Problems:

  • Create a square 2D array of zeros and then replace its diagonal with custom values from a given list.
  • Write a function that accepts an array of diagonal values and outputs a matrix with those values on its diagonal.
  • Validate the custom diagonal by comparing each diagonal element to the expected value.
  • Handle edge cases where the number of diagonal values does not match the matrix size and raise an error.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 3-D array with ones on the diagonal and zeros elsewhere.
Next: Write a NumPy program to create a 1-D array going from 0 to 50 and an array from 10 to 50.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.