w3resource
NumPy Exercises

NumPy: Create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5

NumPy: Basic Exercise-29 with Solution

Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.

Sample Solution :

Python Code :

import numpy as np
x = np.diag([1, 2, 3, 4, 5])
print(x)

Sample Output:

[[1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]
 [0 0 0 0 5]]                         

Pictorial Presentation:

NumPy: Create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.

Python Code Editor:


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

Previous: Write a NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0.
Next: Write a NumPy program to create an 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal.

What is the difficulty level of this exercise?