Raj
Raj

Reputation: 11

How do I convert a Python Array to a SymPy Matrix to calculate the determinant?

I managed to create a python array of this kind :

MainMatrix=[[0 for x in range(n)] for y in range(n)]

(And I changed some values in the Matrix)

Now, I want to know if it is possible to convert this to a SymPy Matrix so that I may calculate the determinant (given all values in the MainMatrix aren't integers and some are SymPy Symbols). I want something of this kind :

M=Matrix([MainMatrix])          #Conversion of Array to SymPy Matrix
M.det()                         #Computation of Determinant of the Matrix

(Yes, I am aware that the first line doesn't work, but I just put it to show my intention)

A solution to this conversion, or any other alternative to find the determinant of the MainMatrix (keeping in mind that all entries aren't integers and some are SymPy Symbols) would be appreciated.

Upvotes: 1

Views: 1443

Answers (2)

asmeurer
asmeurer

Reputation: 91580

Your MainMatrix is already in the correct form. You just need to pass it to sympy.Matrix.

M = Matrix(MainMatrix)

Upvotes: 2

developer_hatch
developer_hatch

Reputation: 16224

Acording to the example of the documentation, Is just simple as doing:

from sympy import *
import math

n=3

n_atoms=8

MainMatrix=Matrix([[0 for x in range(n)] for y in range(n)])

KappaMatrix=Matrix([0 for x in range(n-1)])

MassMatrix=Matrix([0 for x in range(n)])

Kappa=3

ka_by_pi=4

for i in range(1,n):

    KappaMatrix[i-1]=3

for i in range(1,n+1):

    MassMatrix[i-1]=3

for i in range(2,n):

    MainMatrix[i-1]= -KappaMatrix[i-2]/MassMatrix[i-1]

    MainMatrix[i-1]= (KappaMatrix[i-2] + KappaMatrix[i-1])/MassMatrix[i-1]

    MainMatrix[i-1]= -KappaMatrix[i-1]/MassMatrix[i-1]

    MainMatrix[0]=(KappaMatrix[0]+Kappa)/MassMatrix[0]

    MainMatrix[0]=-(KappaMatrix[0])/MassMatrix[0]

    i=symbols('i')

    MainMatrix[0]= -(Kappa/MassMatrix[0])*(math.cos(math.pi*ka_by_pi)+(i*math.sin(math.pi*ka_by_pi)))

    MainMatrix[n-1]= -(Kappa/MassMatrix[n-1])*(math.cos(math.pi*ka_by_pi)-(i*math.sin(math.pi*ka_by_pi)))

    MainMatrix[n-1]=-(KappaMatrix[n-2])/MassMatrix[n-1]

    MainMatrix[n-1]=(KappaMatrix[n-2]+Kappa)/MassMatrix[n-1]

    t=symbols('t')

for j in range(0,n_atoms):
    MainMatrix[j]=MainMatrix[j]-(t**2)

print(MainMatrix)

Upvotes: 1

Related Questions