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.
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]])
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With