Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]] 
like image 251
Tom Kurushingal Avatar asked Feb 19 '15 04:02

Tom Kurushingal


People also ask

How do you convert a matrix to a diagonal matrix?

The steps to diagonalize a matrix are: Find the eigenvalues of the matrix. Calculate the eigenvector associated with each eigenvalue. Form matrix P, whose columns are the eigenvectors of the matrix to be diagonalized.

How do you find the diagonal of a matrix in Python?

The diag function is numpy. diag(v, k=0) where v is an array that returns a diagonal matrix. Specifying v is important, but you can skip k . If v is an array, it returns a diagonal matrix 4x4 with the array elements as the diagonal matrix elements.


1 Answers

You can use diag method:

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) 

Result is again:

[[1 0 0 0]  [0 2 0 0]  [0 0 3 0]  [0 0 0 4]] 
like image 155
Marcin Avatar answered Sep 25 '22 09:09

Marcin