Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build matrices from block matrices in SymPy

I want a matrix looks like this:

import sympy as sp
sp.Matrix([[1,0,2,0],[0,1,0,2],[1,0,2,0],[0,1,0,2]])
# output
#⎡1  0  2  0⎤
#⎢          ⎥
#⎢0  1  0  2⎥
#⎢          ⎥
#⎢1  0  2  0⎥
#⎢          ⎥
#⎣0  1  0  2⎦

I want to construct a new matrix from block matrices:

s=sp.eye(2)
sp.Matrix([[s,2*s],[s,2*s]])
# output:
#⎡⎡1  0⎤  ⎡2  0⎤⎤
#⎢⎢    ⎥  ⎢    ⎥⎥
#⎢⎣0  1⎦  ⎣0  2⎦⎥
#⎢              ⎥
#⎢⎡1  0⎤  ⎡2  0⎤⎥
#⎢⎢    ⎥  ⎢    ⎥⎥
#⎣⎣0  1⎦  ⎣0  2⎦⎦

The output has extra brackets inside.

One solution is by sympy.functions.transpose method:

from sympy.functions import transpose
sp.Matrix([transpose(sp.Matrix([s*i for i in range(1,3)])) for j in range(1,3)])
# output 
#⎡1  0  2  0⎤
#⎢          ⎥
#⎢0  1  0  2⎥
#⎢          ⎥
#⎢1  0  2  0⎥
#⎢          ⎥
#⎣0  1  0  2⎦

This solution is rather tedious. I am wondering if there are better solutions?

In short the sp.Matrix method seems to combine matrices if only they are in a one-dimension list.

like image 464
Xiaoyu Liu Avatar asked May 30 '18 14:05

Xiaoyu Liu


2 Answers

Using TensorProduct:

>>> from sympy import *
>>> from sympy.physics.quantum import TensorProduct
>>> A = ones(2,1) * Matrix([1,2]).T
>>> A
Matrix([
[1, 2],
[1, 2]])
>>> TensorProduct(A, eye(2))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[1, 0, 2, 0],
[0, 1, 0, 2]])

Using BlockMatrix:

>>> from sympy import *
>>> BlockMatrix([[eye(2), 2*eye(2)],[eye(2), 2*eye(2)]])
Matrix([
[Matrix([
[1, 0],
[0, 1]]), Matrix([
[2, 0],
[0, 2]])],
[Matrix([
[1, 0],
[0, 1]]), Matrix([
[2, 0],
[0, 2]])]])
>>> Matrix(BlockMatrix([[eye(2), 2*eye(2)],[eye(2), 2*eye(2)]]))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[1, 0, 2, 0],
[0, 1, 0, 2]])
like image 151
Rodrigo de Azevedo Avatar answered Oct 12 '22 18:10

Rodrigo de Azevedo


You can also use the hstack and vstack functions:

A = eye(2)
B = 2 * eye(2)
Matrix.vstack(
    Matrix.hstack(A, B),
    Matrix.hstack(A, B)
)
like image 38
alcedine Avatar answered Oct 12 '22 18:10

alcedine