So I'm trying to solve system of linear equations using Cramer's Rule and the main issue I'm facing is that I've to create Ax,Ay,...An variables everytime based on the dimension of the matrix. Is there any way in Python by which program can automatically create the variables based on the for loop initiated for dimension of the matrix?
Add a comment
|
1 Answer
I found a python solution (and for almost any other language) here: https://rosettacode.org/wiki/Cramer%27s_rule
from numpy import linalg
A=[[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]
B=[-3,-32,-47,49]
C=[[2,-1,5,1],[3,2,2,-6],[1,3,3,-1],[5,-2,-3,3]]
X=[]
for i in range(0,len(B)):
for j in range(0,len(B)):
C[j][i]=B[j]
if i>0:
C[j][i-1]=A[j][i-1]
X.append(round(linalg.det(C)/linalg.det(A),1))
print('w=%s'%X[0],'x=%s'%X[1],'y=%s'%X[2],'z=%s'%X[3])
5 Comments
Jörn
With python 3.7.3 it gives the result w=2.0 x=-12.0 y=-4.0 z=1.0. What is the error you are encounting?
Sahil Jhawar
I want to use
np.matrix and this code is not working if I typecast the list as np.matrixSahil Jhawar
okay sorry, I made it work, I did some calculations error
Sahil Jhawar
can you make it work for
np.matrix, right now I am using this code by implementing the matrices as np.arrayJörn
You could convert your ABC np.matrix to np.array and it will work. Use: A=A.getA() B=B.getA()[0] C=C.getA() You did not implement your matrixes as np.array. You have np.matrix. However, calling getA() on the np.matrix will return the np.array variant of it.