如何在Python中将列或行矩阵转换为对角矩阵? [英] How to convert a column or row matrix to a diagonal matrix in Python?
本文介绍了如何在Python中将列或行矩阵转换为对角矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个行向量A,A = [a1 a2 a3 ..... an],我想创建一个对角矩阵,B = diag(a1,a2,a3,.....,an )与该行向量的元素.如何在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?
更新
这是说明问题的代码:
import numpy as np
a = np.matrix([1,2,3,4])
d = np.diag(a)
print (d)
此代码的输出为[1],但我想要的输出为:
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]]
推荐答案
您可以使用诊断方法:
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)
结果:
[[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])
结果:
[[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)
结果再次是:
[[1 0 0 0]
[0 2 0 0]
[0 0 3 0]
[0 0 0 4]]
这篇关于如何在Python中将列或行矩阵转换为对角矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文