Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (20.3k points)

I have a row vector A, A = [a1 a2 a3 ..... an] and I would like to create a diagonal matrix, B = diag(a1, a2, a3, ....., an) with the elements of this row vector. How can this be done in Python?

UPDATE

This is the code to illustrate the problem:

import numpy as np

a = np.matrix([1,2,3,4])

d = np.diag(a)

print (d)

the output of this code is [1], but my desired output is:

[[1 0 0 0]

 [0 2 0 0]

 [0 0 3 0]

 [0 0 0 4]]

2 Answers

0 votes
by (40.7k points)

You can try using diag method like this:

import numpy as np

a = np.array([1,2,3,4])

d = np.diag(a)

# or simpler: d = np.diag([1,2,3,4])

print(d)

Results in:

[[1 0 0 0]

 [0 2 0 0]

 [0 0 3 0]

 [0 0 0 4]]

If you have a row vector, you can do this:

a = np.array([[1, 2, 3, 4]])

d = np.diag(a[0])

Results in:

[[1 0 0 0]

 [0 2 0 0]

 [0 0 3 0]

 [0 0 0 4]]

For the given matrix in the question:

import numpy as np

a = np.matrix([1,2,3,4])

d = np.diag(a.A1)

print (d)

The result is again:

[[1 0 0 0]

 [0 2 0 0]

 [0 0 3 0]

 [0 0 0 4]]

If you wish to learn more about Python, visit the Python tutorial and Python course by Intellipaat. 

0 votes
by (106k points)

To convert a column or row matrix into a diagonal you can use diagflat:

import numpy 

a = np.matrix([1,2,3,4]) 

d = np.diagflat(a) 

print (d)

Related questions

0 votes
1 answer
asked Oct 15, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Mar 21, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Sep 24, 2019 in Python by Sammy (47.6k points)
+1 vote
1 answer
asked Jul 31, 2019 in Python by Eresh Kumar (45.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...