Back from matrix form to linear form in SymPy

Viewed 60

I am learning linear algebra in SymPy. I have equations with Pauli matrices.

Let's say I have

sigma_0 = Matrix([[1, 0],[0, 1]])
sigma_1 = Matrix([[0, 1],[1, 0]])
sigma_2 = Matrix([[0, -I],[I, 0]])

Now, I want to do some basics algebra like

sigma_1 + 2*sigma_2

As a result it gives me matrix. And I want to convert it as sigma_1 + 2*sigma_2. How to convert it from matrix form to linear form?

2 Answers

What you actually want to do is to simplify an expression that will potentially contain any of these matrices. In fact, it has nothing to do with the matrices themselves but rather with simplifications. So what I suggest is the following:

import numpy as np
import sympy
from sympy import *
from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)

def function_simplifier(x,y,z,a,b,c):
    return simplify(a*x +b*y +c*z)

so, for

2*sigma_1 + sigma_2 - 5*sigma_1

This would be:

function_simplifier(y,z,y,2,1,-5)

which returns:

-3*y + z

Now, if you want to calculate the result:

A = simplify(function_simplifier(y,z,y,2,1,-5))
f = lambdify((x,y,z),A)

f(sigma_0,sigma_1,sigma_2)

which will return the matrix

Matrix([[0, -3 - I], [-3 + I, 0]])

You could use MatrixSymbols and then substitute in the matrices when you want to see the actual value:

>>> from sympy import Matrix, MatrixSymbol
>>> sigma_0 = Matrix([[1, 0],[0, 1]])
>>> sigma_1 = Matrix([[0, 1],[1, 0]])
>>> sigma_2 = Matrix([[0, -I],[I, 0]])
>>> a,b,c = [MatrixSymbol(i,2,2) for i in 'ABC']
>>> 2*a+b-3*a
-A + B
>>> _.subs({a: sigma_0, b:sigma_1})
Matrix([
[0, 1],
[1, 0]]) - Matrix([
[1, 0],
[0, 1]])
>>> _.doit()  # or _.subs(...).doit(), too
Matrix([
[-1,  1],
[ 1, -1]])
Related