【问题标题】:2D array with 2D arrays on the diagonal二维数组,对角线上有二维数组
【发布时间】:2020-07-24 19:26:46
【问题描述】:

我有矩阵

J_plus = 
    [[ 0.0609698  -0.00022921 -0.00022921 ... -0.00022921 -0.00022921
    -0.00022921]
    [-0.00022921  0.0609698  -0.00022921 ... -0.00022921 -0.00022921
    -0.00022921]
    [-0.00022921 -0.00022921  0.0609698  ... -0.00022921 -0.00022921
    -0.00022921]
    ...
    [-0.00022921 -0.00022921 -0.00022921 ...  0.0609698  -0.00022921
    -0.00022921]
    [-0.00022921 -0.00022921 -0.00022921 ... -0.00022921  0.0609698
    -0.00022921]
    [-0.00022921 -0.00022921 -0.00022921 ... -0.00022921 -0.00022921
     0.0609698 ]]

J_minus: 
    [[ 4.46319168e-02 -8.94427191e-05 -8.94427191e-05 ... -8.94427191e-05
     -8.94427191e-05 -8.94427191e-05]
     [-8.94427191e-05  4.46319168e-02 -8.94427191e-05 ... -8.94427191e-05
     -8.94427191e-05 -8.94427191e-05]
     [-8.94427191e-05 -8.94427191e-05  4.46319168e-02 ... -8.94427191e-05
     -8.94427191e-05 -8.94427191e-05]
     ...
     [-8.94427191e-05 -8.94427191e-05 -8.94427191e-05 ...  4.46319168e-02
     -8.94427191e-05 -8.94427191e-05]
     [-8.94427191e-05 -8.94427191e-05 -8.94427191e-05 ... -8.94427191e-05
     4.46319168e-02 -8.94427191e-05]
     [-8.94427191e-05 -8.94427191e-05 -8.94427191e-05 ... -8.94427191e-05
     -8.94427191e-05  4.46319168e-02]]

如何创建矩阵

J = [[J_plus   0];
    [0        J_minus]]

所以最终的矩阵应该是一个 2X2 对角矩阵,其中 J_plus 和 J_minus 作为对角元素,像这样

J = [ J_plus    0;
    0         J_minus] 

在 numpy 中?

【问题讨论】:

  • 你可以使用np.block
  • shapedtype 的结果是什么?你打算用它做什么?
  • 尝试分配您喜欢的形状的矩阵并使用切片进行分配,例如M[0, 0:-1] = J_plus.
  • 是的@desertnaut,因为这个方程来自机器学习论文,所以我错误地贴上了机器学习的标签。

标签: python-3.x numpy matrix scipy


【解决方案1】:

最简单的方法:scipy.linalg.block_diag

linalg.block_diag(J_plus, J_minus)

基于Numpy的方法,我们可以使用np.block。虽然这绝对不是在堆叠多个阵列时去的方式:

px, py = J_plus.shape
mx, my = J_minus.shape

np.block([[J_plus,              np.zeros((px, my))], 
          [np.zeros((py, mx)),  J_minus]])

例如:

a = np.arange(16).reshape(4,4)
b = np.arange(24).reshape(4,6)

linalg.block_diag(a, b)

array([[ 0.,  1.,  2.,  3.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 4.,  5.,  6.,  7.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 8.,  9., 10., 11.,  0.,  0.,  0.,  0.,  0.,  0.],
       [12., 13., 14., 15.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.],
       [ 0.,  0.,  0.,  0.,  6.,  7.,  8.,  9., 10., 11.],
       [ 0.,  0.,  0.,  0., 12., 13., 14., 15., 16., 17.],
       [ 0.,  0.,  0.,  0., 18., 19., 20., 21., 22., 23.]])

【讨论】:

    猜你喜欢
    • 2011-05-25
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多