# 从稀疏coo_matrix获得的对角稀疏矩阵Diagonal sparse matrix obtained from a sparse coo_matrix

``````A = M + M.T - D
``````

`D = scipy.sparse.spdiags(coo_matrix.diagonal(M),0,M.shape[0],M.shape[0])`是解决方案吗？

## 2 个回复2

### #1楼 票数：1 已采纳

``````msk = M.row==M.col
D1 = sparse.coo_matrix((M.data[msk],(M.row[msk],M.col[msk])),shape=M.shape)
``````

`sparse.tril`使用此方法时`mask = A.row + k >= A.col``sparse/extract.py`

``````In [303]: timeit msk=M.row==M.col; D1=sparse.coo_matrix((M.data[msk],(M.row[msk],M.col[msk])),shape=M.shape)
10000 loops, best of 3: 115 µs per loop

In [305]: timeit D=sparse.diags(M.diagonal(),0)
1000 loops, best of 3: 358 µs per loop
``````

``````In [306]: timeit D=sparse.diags(M1.diagonal(),0)
10000 loops, best of 3: 176 µs per loop
``````

``````In [307]: timeit M+M.T-D
1000 loops, best of 3: 1.35 ms per loop

In [308]: timeit M1+M1.T-D
1000 loops, best of 3: 1.11 ms per loop
``````

``````def MplusMT(M):
msk=M.row!=M.col;
data=np.concatenate([M.data, M.data[msk]])
rows=np.concatenate([M.row, M.col[msk]])
cols=np.concatenate([M.col, M.row[msk]])
MM=sparse.coo_matrix((data, (rows, cols)), shape=M.shape)
return MM

# alt version with a more explicit D
#    msk=M.row==M.col;
#    data=np.concatenate([M.data, M.data,-M.data[msk]])
``````

``````MplusMT(M).tocsr()
``````

### #2楼 票数：0

``````from scipy.sparse import diags
D = diags(M.diagonal(), 0, format='coo')
``````

1回复

1回复

3回复

1回复

2回复

2回复

1回复

3回复