如何在SciPy中创建对角稀疏矩阵 [英] How to create a diagonal sparse matrix in SciPy

查看:313
本文介绍了如何在SciPy中创建对角稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个稀疏矩阵,该矩阵具有沿对角线排列的2D模式.举个简单的例子,这可能最容易解释.

I am trying to create a sparse matrix which has a 2D pattern run down the diagonal. This is probably easiest to explain with a quick example.

说我的模式是:[1,0,2,0,1] ...

Say my pattern is: [1,0,2,0,1]...

我想创建一个稀疏矩阵:

I want to create a sparse matrix:

    [[2,0,1,0,0,0,0...0],
     [0,2,0,1,0,0,0...0],
     [1,0,2,0,1,0,0...0],
     [0,1,0,2,0,1,0...0],
     [0,0,1,0,2,0,1...0],
     [...]]

scipy.sparse.dia_matrix似乎是一个不错的选择,但是,我根本无法从现有文档中弄清楚如何完成我想要的工作.预先谢谢你

The scipy.sparse.dia_matrix seems like a good candidate, however, I simply cannot figure out how to accomplish what I want from the documentation available. Thank you in advance

推荐答案

N = 10
diag = np.zeros(N) + 2
udiag = np.zeros(N) + 1
ldiag = np.zeros(N) + 1
mat = scipy.sparse.dia_matrix(([diag, udiag, ldiag], [0, 2, -2]), shape=(N, N))
print mat.todense()
[[ 2.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  2.  0.  1.  0.  0.  0.  0.  0.  0.]
[ 1.  0.  2.  0.  1.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  2.  0.  1.  0.  0.  0.  0.]
[ 0.  0.  1.  0.  2.  0.  1.  0.  0.  0.]
[ 0.  0.  0.  1.  0.  2.  0.  1.  0.  0.]
[ 0.  0.  0.  0.  1.  0.  2.  0.  1.  0.]
[ 0.  0.  0.  0.  0.  1.  0.  2.  0.  1.]
[ 0.  0.  0.  0.  0.  0.  1.  0.  2.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  1.  0.  2.]]

这篇关于如何在SciPy中创建对角稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆