【问题标题】:Inserting sub-matrices into scipy sparse matrix将子矩阵插入 scipy 稀疏矩阵
【发布时间】:2019-05-06 12:51:53
【问题描述】:

如何有效地将特定位置的子矩阵插入我的稀疏矩阵?另外,对于这种增量构造,推荐使用哪个 scipy 稀疏矩阵类?

更具体地说,如何在下面的代码中填充矩阵M?

def rrd(mesh, rel_rotations, neighbors, R_0):
    M = scipy.sparse.lil_matrix((N_FACES*9*3,N_FACES*9))
    for i in range(0,N_FACES*27,27):
        for j in range(3):
            for k in range(0,N_FACES*9,9):
                M[i+j*9:i+(j+1)*9,k:k+9] = -np.eye(9)
    for i in range(len(rel_rotations)):
        diagonals = [
            rel_rotations[i][0][2],
            np.append(rel_rotations[i][0][1].repeat(3), rel_rotations[i][1][2].repeat(3)),
            np.append(rel_rotations[i][0][0].repeat(3), np.append(rel_rotations[i][1][1].repeat(3), 
            rel_rotations[i][2][2].repeat(3))),
            np.append(rel_rotations[i][1][0].repeat(3), rel_rotations[i][2][1].repeat(3)),
            rel_rotations[i][2][0].repeat(3)
        ]
        diag_rel_rotations = scipy.sparse.diags(diagonals, [-6,-3,0,3,6], shape=(9,9)).todense()
        mod = i % 3
        div = int((i-mod)/3)
        n_idx = neighbors[div][mod]
        M[i+mod*9:i+(mod+1)*9][n_idx*9:(n_idx+1)*9] = diag_rel_rotations

切片在这里不起作用,我查看了一些不同类型的稀疏矩阵,但无法确定哪个适合这个问题。

【问题讨论】:

  • 请分享您的代码以及您已经完成/查看的内容。另外,请查看有关如何提问的指南:How do I ask a question?
  • 好的,我这样做了,希望现在更清楚了。
  • M[i+j*9:i+(j+1)*9][k:k+9] = ... 甚至不适用于ndarraynumpy 索引最好用A[i, j] 完成,一组括号。不要只说“切片在这里不起作用”;向我们展示您的问题(错误、回溯)。退一步测试一个简单的案例也可能会有所帮助 - 将一个简单的 (3,3) 分配给 (9,9) 。使 if 为 ndarray 工作,然后尝试稀疏。

标签: python scipy sparse-matrix


【解决方案1】:

lil 是正确的分配对象。

In [553]: M = sparse.lil_matrix((9,9), dtype=int)                                    
In [554]: M                                                                          
Out[554]: 
<9x9 sparse matrix of type '<class 'numpy.int64'>'
    with 0 stored elements in LInked List format>

In [555]: M[2:5, 3:6] = np.eye(3)                                                    
In [556]: M                                                                          
Out[556]: 
<9x9 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in LInked List format>
In [557]: M.A                                                                        
Out[557]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0]])

In [558]: d = sparse.diags([[1,2],[1,2,3],[2,3]], [-1,0,1]) 
In [562]: M[0:3, 6:9] = d 

【讨论】:

  • 非常感谢,你太棒了:) 显然我在发帖之前并没有考虑太多这个问题。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 2017-07-21
  • 2011-11-28
  • 2017-07-02
  • 2011-03-07
相关资源
最近更新 更多