如何重复使用block_diag [英] How to use block_diag repeatedly
问题描述
我有一个非常简单的问题,但仍然无法解决.
我想要一个块对角n ^ 2 * n ^ 2矩阵.块是只有对角线的稀疏n * n矩阵,首先是对角线,然后是对角线.对于n=4
的简单情况,可以轻松完成
I have rather simple question but still couldn´t make it work.
I want a block diagonal n^2*n^2 matrix. The blocks are sparse n*n matrices with just the diagonal, first off diagonals and forth off diag. For the simple case of n=4
this can easily be done
datanew = ones((5,n1))
datanew[2] = -2*datanew[2]
diagsn = [-4,-1,0,1,4]
DD2 = sparse.spdiags(datanew,diagsn,n,n)
new = sparse.block_diag([DD2,DD2,DD2,DD2])
由于这仅对小n有用,是否有更好的方法来使用block_diag? n-> 1000的思考
Since this only useful for small n's, is there a way better way to use block_diag? Thinking of n -> 1000
推荐答案
构造DD2
矩阵长列表的一种简单方法是使用列表理解:
A simple way of constructing a long list of DD2
matrices, is with a list comprehension:
In [128]: sparse.block_diag([DD2 for _ in range(20)]).A
Out[128]:
array([[-2, 1, 0, ..., 0, 0, 0],
[ 1, -2, 1, ..., 0, 0, 0],
[ 0, 1, -2, ..., 0, 0, 0],
...,
[ 0, 0, 0, ..., -2, 1, 0],
[ 0, 0, 0, ..., 1, -2, 1],
[ 0, 0, 0, ..., 0, 1, -2]])
In [129]: _.shape
Out[129]: (80, 80)
至少在我的版本中,block_diag
想要一个数组列表,而不是*args
:
At least in my version, block_diag
wants a list of arrays, not *args
:
In [133]: sparse.block_diag(DD2,DD2,DD2,DD2)
...
TypeError: block_diag() takes at most 3 arguments (4 given)
In [134]: sparse.block_diag([DD2,DD2,DD2,DD2])
Out[134]:
<16x16 sparse matrix of type '<type 'numpy.int32'>'
with 40 stored elements in COOrdinate format>
这可能不是构造这样的块对角线数组的最快方法,但这是一个开始.
This probably isn't the fastest way to construct such a block diagonal array, but it's a start.
================
================
看看sparse.block_mat
的代码,我推断它确实可以做到:
Looking at the code for sparse.block_mat
I deduce that it does:
In [145]: rows=[]
In [146]: for i in range(4):
arow=[None]*4
arow[i]=DD2
rows.append(arow)
.....:
In [147]: rows
Out[147]:
[[<4x4 sparse matrix of type '<type 'numpy.int32'>'
with 10 stored elements (5 diagonals) in DIAgonal format>,
None,
None,
None],
[None,
<4x4 sparse matrix of type '<type 'numpy.int32'>'
...
None,
<4x4 sparse matrix of type '<type 'numpy.int32'>'
with 10 stored elements (5 diagonals) in DIAgonal format>]]
换句话说,rows
是None
的矩阵",沿着对角线是DD2
.然后将它们传递给sparse.bmat
.
In other words, rows
is a 'matrix' of None
with DD2
along the diagonals. It then passes these to sparse.bmat
.
In [148]: sparse.bmat(rows)
Out[148]:
<16x16 sparse matrix of type '<type 'numpy.int32'>'
with 40 stored elements in COOrdinate format>
bmat
依次从所有输入矩阵的coo
格式中收集data,rows,cols
,将它们连接到主数组中,并从它们中构建一个新的coo
矩阵.
bmat
in turn collects the data,rows,cols
from the coo
format of all the input matricies, joins them into master arrays, and builds a new coo
matrix from them.
因此,一种替代方法是直接构造这3个数组.
So an alternative is to construct those 3 arrays directly.
这篇关于如何重复使用block_diag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!