如何在 Python 中将列或行矩阵转换为对角矩阵?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28598572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a column or row matrix to a diagonal matrix in Python?
提问by Tom Kurushingal
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?
我有一个行向量 A, A = [a1 a2 a3 ..... an] 并且我想创建一个对角矩阵 B = diag(a1, a2, a3, ....., an) 与此行向量的元素。这如何在 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],但我想要的输出是:
[[1 0 0 0]
[0 2 0 0]
[0 0 3 0]
[0 0 0 4]]
采纳答案by Marcin
You can use diagmethod:
您可以使用diag方法:
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]]
回答by deadcode
Assuming you are working in numpy based on your tags, this will do it:
假设您根据标签在 numpy 中工作,则可以这样做:
import numpy
def make_diag( A ):
my_diag = numpy.zeroes( ( 2, 2 ) )
for i, a in enumerate( A ):
my_diag[i,i] = a
return my_diag
enumerate( LIST ) creates an iterator over the list that returns tuples like:
enumerate( LIST ) 在列表上创建一个迭代器,返回元组,如:
( 0, 1st element), ( 1, 2nd element), ... ( N-1, Nth element )
( 0, 1st element), ( 1, 2nd element), ... ( N-1, Nth element )
回答by Bokee
回答by jeannej
Another solution could be:
另一种解决方案可能是:
import numpy as np
a = np.array([1,2,3,4])
d = a * np.identity(len(a))
As for performances for the various answers here, I get with timeit
on 100000 repetitions:
至于这里各种答案的表现,我得到了timeit
100000 次重复:
np.array
andnp.diag
(Marcin's answer): 2.18E-02 snp.array
andnp.identity
(this answer): 6.12E-01 snp.matrix
andnp.diagflat
(Bokee's answer): 1.00E-00 s
np.array
和np.diag
(Marcin 的回答):2.18E-02 snp.array
和np.identity
(这个答案):6.12E-01 snp.matrix
和np.diagflat
(Bokee 的回答):1.00E-00 秒