[Numpy-discussion] how to create a block diagonal matrix by repeating the block?
Warren Weckesser
warren.weckesser@enthought....
Thu Aug 11 21:01:03 CDT 2011
On Thu, Aug 11, 2011 at 7:15 PM, Fernando Perez <fperez.net@gmail.com>wrote:
> On Thu, Aug 11, 2011 at 4:43 PM, Jose Borreguero <borreguero@gmail.com>
> wrote:
> > a = random.randn(3,3)
> > b = a.reshape(1,3,3).repeat(50,axis=0)
> > scipy.linalg.block_diag( *b )
> >
>
> slightly simpler, but equivalent, code:
>
> b = [a]*50
> scipy.linalg.block_diag( *b)
>
>
The following is unnecessarily complicated--using block_diag is fine--but it
can be fun to stretch out into the fourth dimension with stride tricks:
from numpy import array, zeros
from numpy.lib.stride_tricks import as_strided
# N is the number of 3x3 blocks.
# N = 50
N = 4
a = array([[1,2,3],[4,5,6],[7,8,9]])
# b will be the block-diagonal array.
b = zeros((3*N, 3*N), dtype=a.dtype)
bstr = b.strides
c = as_strided(b, shape=(N,N,3,3), strides=(3*bstr[0], 3*bstr[1], bstr[0],
bstr[1]))
# Assign a to the diagonal blocks.
c[range(N), range(N)] = a
print b
Output:
[[1 2 3 0 0 0 0 0 0 0 0 0]
[4 5 6 0 0 0 0 0 0 0 0 0]
[7 8 9 0 0 0 0 0 0 0 0 0]
[0 0 0 1 2 3 0 0 0 0 0 0]
[0 0 0 4 5 6 0 0 0 0 0 0]
[0 0 0 7 8 9 0 0 0 0 0 0]
[0 0 0 0 0 0 1 2 3 0 0 0]
[0 0 0 0 0 0 4 5 6 0 0 0]
[0 0 0 0 0 0 7 8 9 0 0 0]
[0 0 0 0 0 0 0 0 0 1 2 3]
[0 0 0 0 0 0 0 0 0 4 5 6]
[0 0 0 0 0 0 0 0 0 7 8 9]]
Warren
Cheers,
>
> f
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110811/aee32258/attachment.html
More information about the NumPy-Discussion
mailing list