Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

How to convert a column or row matrix to a diagonal matrix in Python?

Asked by Charles Parr Apr 14, 2021 1.1K views 1 answer
Share

About this question

 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]]

Your answer

1 Answer

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.