I can't figure it out what's wrong with my code, it's rly frustrating. I have to make inverse matrix function, what I thought I've done. I don't know why it doesn't work. The problem is probably in line with stars, after this step my matrix named mat is changed to identity matrix, but why? Before stars it prints my mat matrix normaly which I gave to function, but after stars it's a identity matrix, I don't understand why it happend. Here's what I have:
def identity_matrix_convertion(m):
x = m[:]
for i in range(len(x)):
for j in range(len(x[0])):
if i == j:
x[i][j] = 1
else:
x[i][j] = 0
return x
def inverse_matrix(mat):
n = len(mat)
am = mat[:]
show_matrix(mat)
**i = identity_matrix_convertion(am)**
show_matrix(mat)
im = i[:]
ind = list(range(n))
print(len(mat))
if determinant(mat) == 0:
print("This matrix doesn't have an inverse.")
if len(mat) == len(mat[0]):
for i in range(n):
scal = 1.0 / am[i][i]
for j in range(n):
am[i][j] *= scal
im[i][j] *= scal
for k in ind[0:i] + ind[i + 1:]:
current_scal = am[k][i]
for l in range(n):
am[k][l] = am[k][l] - current_scal * am[i][j]
im[k][l] = im[k][l] - current_scal * im[i][j]
return im
so after line **i = identity_matrix_convertion(am)** my mat matrix is changed into identity matrix, but why?
The result is:
1.0 2.0 3.0
2.0 1.0 3.0
4.0 3.0 2.0
The result is:
1 0 0
0 1 0
0 0 1
Instead of saying x = m[:]
in the identity_matrix_convertion()
function, you should add the following snippet:
x = []
for i in m:
arr = [a for a in i]
x.append(arr)
x = m[:]
is still referencing m instead of just making a copy.