I'm trying to solve a 3x3 matrix using cramer's rule and as I'm new to python I'm finding it difficult to figure out my answer alone I've been doing research on how to do it using different methods but I've came to a stop near the end of it. The reason on why that it has to be with no packages is because I have to do it for homework and I have to find out for every possible matrix I've altered the one I originally had to try and find every matrix but since I'm still learning python it hasn't gone to plan
``
# determinant of Matrix
def determinantOfMatrix(mat):
ans = (mat[0][0] * mat[1][1] * mat[2][2] +
(mat[0][1] * mat[1][2] * mat[2][0])
+ (mat[0][2] * mat[1][0] * mat[2][1] -
(mat[0][2] * mat[1][1] * mat[2][0]
+ mat[0][0] * mat[1][2] * mat[2][1] +
mat[0][1] * (mat[1][0] * mat[2][2]))))
return ans
# linear equations using cramer's rule
def findSolution(coeff):
# Matrix d
d = [[coeff[0][0], coeff[0][1], coeff[0][2]],
[coeff[1][0], coeff[1][1], coeff[1][2]],
[coeff[2][0], coeff[2][1], coeff[2][2]]]
# Matrix d1 using coeff as given in
# cramer's rule
d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]],
[coeff[1][3], coeff[1][1], coeff[1][2]],
[coeff[2][3], coeff[2][1], coeff[2][2]]]
# Matrix d2 using coeff as given in
# cramer's rule
d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]],
[coeff[1][0], coeff[1][3], coeff[1][2]],
[coeff[2][0], coeff[2][3], coeff[2][2]]]
# Matrix d3 using coeff as given in
# cramer's rule
d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]],
[coeff[1][0], coeff[1][1], coeff[1][3]],
[coeff[2][0], coeff[2][1], coeff[2][3]]]
# Calculating Determinant of Matrices
# d, d1, d2, d3
D = determinantOfMatrix(d)
D1 = determinantOfMatrix(d1)
D2 = determinantOfMatrix(d2)
D3 = determinantOfMatrix(d3)
# print("D is : ", D)
print("D1 is : ", D1)
print("D2 is : ", D2)
print("D3 is : ", D3)
# Case 1
if D != 0:
x = D1 / D
y = D2 / D
z = D3 / D
print("Value of x is : ", x)
print("Value of y is : ", y)
print("Value of z is : ", z)
# Case 2
else:
if (D1 == 0 and D2 == 0 and
D3 == 0):
print("Infinite solutions")
elif (D1 != 0 or D2 != 0 or
D3 != 0):
print("No solutions")
if __name__ == "__main__":
row = int(input("Enter number of rows you want: "))
col = int(input("Enter number of columns you want: "))
coeff = []
for m in range(row):
a = []
for n in range(col):
a.append(0)
coeff.append(a)
for i in range(len(coeff)):
for j in range(len(coeff[0])):
coeff[i][j] = int(input("Input element: "))
print("Your Matrix is :", coeff)
findSolution(coeff)
``
What's expected is that I'm trying to find out x,y and z from every possible matrix that the user inputs if its a 3x3 matrix but I can't figure out on how I can have two different matrices on the same memory"[0][0]" using this method and I can't find any solutions on my problem. The error message that I get is that the list index is out of range because there is no [3] within my matrix if there's anyone that can help me I will appreciate it greatly