一个矩阵的伴随矩阵不用现成的库(numpy)怎么求,首先看一下公式:
def remove_line(index,arr):
yy=[]
for i in range(len(arr)):
hh=[]
for j in range(len(arr)):
if(i==index[0] or j==index[1]):
pass
else:
hh.append(arr[i][j])
if(hh!=[]):
yy.append(hh)
# yy.remove([])
return yy
dd=[[0,4,3,5],[2,3,2,6],[3,4,5,7],[3,4,5,7]]
for i in range(len(dd)):
for j in range(len(dd)):
tm_list=remove_line(tuple([i,j]),dd)
print((i,j),tm_list)
的求法就是这样
怎么求代数余子式呢,就是求矩阵的行列式
def getInversion(numlist):
count = 0
for i in range(1,len(numlist)):
subscript = numlist[i]
for j in range(i):
if subscript < numlist[j]:
count += 1
return count
def remove_line(index,arr):
yy=[]
for i in range(len(arr)):
hh=[]
for j in range(len(arr)):
if(i==index[0] or j==index[1]):
pass
else:
hh.append(arr[i][j])
if(hh!=[]):
yy.append(hh)
# yy.remove([])
return yy
def permutation(dd,ilist,jlist,index):
# global D
# D = 0
for i in range(index,len(jlist)):
if index == len(jlist)-1:
term = 1
for ii in range(len(ilist)):
i = ilist[ii]
j = jlist[ii]
term *= dd[i][j]
if getInversion(jlist) % 2 == 0:
Matrix.global_d_value += term
else:Matrix.global_d_value -= term
return
tmp = jlist[index]
jlist[index] = jlist[i]
jlist[i] = tmp
permutation(dd,ilist,jlist,index+1)
tmp = jlist[index]
jlist[index] = jlist[i]
jlist[i] = tmp
class Matrix:
"""docstring for Matrix"""
global_d_value=0
dd=[[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(dd)):
for j in range(len(dd)):
tm_list=remove_line(tuple([i,j]),dd)
ilist=[i for i in range(len(tm_list))]
jlist=[i for i in range(len(tm_list))]
# i,j位置的余子式
print((i,j),tm_list)
Matrix.global_d_value=0
permutation(tm_list,ilist,jlist,0)
# i,j位置的代数余子式
print((i,j),Matrix.global_d_value)
结果:
(0, 0) [[5, 6], [8, 9]]
(0, 0) -3
(0, 1) [[4, 6], [7, 9]]
(0, 1) -6
(0, 2) [[4, 5], [7, 8]]
(0, 2) -3
(1, 0) [[2, 3], [8, 9]]
(1, 0) -6
(1, 1) [[1, 3], [7, 9]]
(1, 1) -12
(1, 2) [[1, 2], [7, 8]]
(1, 2) -6
(2, 0) [[2, 3], [5, 6]]
(2, 0) -3
(2, 1) [[1, 3], [4, 6]]
(2, 1) -6
(2, 2) [[1, 2], [4, 5]]
(2, 2) -3
[Finished in 0.1s]
有了这个就可以用伴随矩阵的方法求逆矩阵了