python实现求矩阵行列式、求逆矩阵等各种矩阵操作(不使用numpy包)

def submatrix(A,i,j):
    #矩阵A第i行第j列元素的余矩阵
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    C=[[A[x][y] for y in range(q) if y!=j] for x in range(p) if x!=i]#列表推导式
    return C
def det(A):
    #按第一行展开递归求矩阵的行列式
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    if(p==1 and q==1):
        return A[0][0]
    else:
        value=0
        for j in range(q):
            value+=((-1)**(j+2))*A[0][j]*det(submatrix(A,0,j))
        return value
def INVERSE(A):
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    C=copy.deepcopy(A)
    d=det(A)
    print(d)
    for i in range(p):
        for j in range(q):
            C[i][j]=((-1)**(i+j+2))*det(submatrix(A,j,i))
            C[i][j]=C[i][j]/d
    print(C)
#不使用numpy实现矩阵操作
def ADD(A,B):
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    C=copy.deepcopy(A)
    for i in range(p):
        for j in range(q):
            C[i][j]=A[i][j]+B[i][j]
    print(C)
def SUBTRACT(A,B):
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    C=copy.deepcopy(A)
    for i in range(p):
        for j in range(q):
            C[i][j]=A[i][j]-B[i][j]
    print(C)
def SCALA_MULTIPLY(A,num):
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    C=copy.deepcopy(A)
    for i in range(p):
        for j in range(q):
            C[i][j]=A[i][j]*num
    print(C)
def MULTIPLY(A,B):
    p=len(A)#矩阵A的行数
    q=len(A[0])#矩阵A的列数=矩阵B的行数
    r=len(B[0])#矩阵B的列数
    C=[[0 for j in range(r)] for i in range(p)]
    for i in range(p):
        for j in range(r):
            for k in range(q):
                C[i][j]+=A[i][k]*B[k][j]
    print(C)
def IDENTITY(dim):
    #生成对角矩阵
    C=[[0 for j in range(dim)] for i in range(dim)]
    for i in range(dim):
        C[i][i]=1
    print(C)
def TRANSPOSE(A):
    p=len(A)#矩阵的行数
    q=len(A[0])#矩阵的列数
    C=copy.deepcopy(A)
    for i in range(p):
        for j in range(q):
            C[i][j]=A[j][i]
    print(C)

你可能感兴趣的:(python操作,python,矩阵,逆运算)