numpy用另一个矩阵填充矩阵对角线值

时间:2019-03-02 02:00:42

标签: python numpy

这是通过另一个整个矩阵填充矩阵对角线元素的简便方法吗?

{{$error}}

我希望结果将是

 heroku deploy:jar target/*.jar -a medscanner2
-----> Packaging application...
   - app: medscanner2
   - including: target/medscanner2.jar
   ! ERROR: Could not get API key! Please install the Heroku CLI and run 
   `heroku login` or set the HEROKU_API_KEY environment variable.
   ! Re-run with HEROKU_DEBUG=1 for more info.
   !There was a problem deploying to medscanner2.
   !Make sure you have permission to deploy by running: heroku apps:info -a 
    medscanner2

4 个答案:

答案 0 :(得分:3)

您的方法有效:

import numpy as np

b = [1,2,3,4,5,6,7,8,9]
a = np.zeros((9, 9), int)

np.fill_diagonal(a, b)

替代方法:

a[np.diag_indices_from(a)] = b

答案 1 :(得分:1)

检查

a[[np.arange(len(b))]*2]=b
a
Out[163]: 
array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 3, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 4, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 5, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 6, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 8, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 9]])

答案 2 :(得分:1)

这是numpy.diag做的事情之一:

a = numpy.diag(b)

答案 3 :(得分:1)

np.eye只是为了娱乐而已。

np.eye(a.shape[0], dtype=int) * b

array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 3, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 4, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 5, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 6, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 8, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 9]])

如果diagflat的尺寸大于1D,也可以使用b

np.diagflat(b)
# np.diagflat([b])
# np.diagflat(np.array([b]))

array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 3, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 4, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 5, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 6, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 7, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 8, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 9]])