不使用numpy完成对矩阵的操作

Posted MirrorML

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了不使用numpy完成对矩阵的操作相关的知识,希望对你有一定的参考价值。

不使用numpy完成对矩阵的操作

​ 众所周知,矩阵操作是进行数据分析的必要操作,而一般进行numpy便能对矩阵进行轻松操作。这里我尝试使用python手动编写对矩阵的操作。

矩阵输出

def print_matrix(A,lable=''):
    if lable=='':
        pass
    else:
        print(lable+"=")
    print('[',end='')
    sum=0
    for i in A:
        print('[',end='')
        count=0
        for j in i:
            count+=1
            if count == len(i):
                print(" %2.2f " %j,end='')
            else:
                print(" %2.2f ,"%j, end='')
        sum+=1
        if sum==len(A ):
            print(']',end='')
            print(']')
        else:
            print(']')

零矩阵生成

def zeros(x,y=''):
    if y=='':
        return [[0] * x for i in range(x)]
    return [[0] * x for i in range(y)]

对角矩阵

def  identity_matrix(n):
    list =zeros(n)
    for i in range(0,n):
        for j in range(0,n):
            if(i==j):
                list[i][j]=1
    return list

交换矩阵两行

def swap_rows(M, src, dest):
    M[src],M[dest] = M[dest],M[src]
    pass

将矩阵某行乘某值

def mult_row_scalar(M, row, scalar):
    for i in range(len(M[row])):
        M[row][i]=M[row][i]*scalar
    pass

将矩阵某行加上某行

def add_row_into(M, src, dest):
    for i in range(len(M[dest])):
        M[dest][i] = M[dest][i]+M[src][i]
    pass

两个矩阵相加

def add_matrices(A, B):
    assert len(A[0]) == len(B[0]), 'error'
    assert  len(A)==len(B) ,  'error'
    for i in range(len(A)):
        for j in range(len(A[i])):
            A[i][j]=A[i][j]+B[i][j]
    return A

两个矩阵相减

def sub_matrices(A, B):
    assert len(A[0]) == len(B[0]), 'error'
    assert len(A) == len(B), 'error'
    for i in range(len(A)):
        for j in range(len(A[i])):
            A[i][j]=A[i][j]-B[i][j]
    return A

矩阵乘法

def mult_scalar(M, s):
    for i in range(len(M)):
        for j in range(len(M[i])):
            M[i][j]=M[i][j]*s
    return M

矩阵点积

def dot_product(M, N):
    c = []
    for i in range(0, len(M)):
        temp = []
        for j in range(0, len(N[0])):
            s = 0
            for k in range(0, len(M[0])):
                s += M[i][k] * N[k][j]
            temp.append(s)
        c.append(temp)
    return c

取矩阵的任意行列

def create_sub_matrix1(M, exclude_row,exclude_col ):
    A=M.copy()
    del A[exclude_row]
    print_matrix(A)
    for i in range(len(A)):
        if(exclude_col==len(M[i])):
            del A[i][exclude_col]
            break
        else:
            for j in range(exclude_col,len(M[i])-1):
                A[i][j]=A[i][j+1]
    l=[]
    for i in range(0, len(M)-1):
        temp = []
        for j in range(0, len(M[0])-1):
            s = 0
            s=A[i][j]
            temp.append(s)
        l.append(temp)
    return l

矩阵行列式

def determinant1(matrix, mul=1):
    width = len(matrix)
    if width == 1:
        return mul * matrix[0][0]
    else:
        sign = -1
        sum = 0
        for i in range(width):
            m = []
            for j in range(1, width):
                buff = []
                for k in range(width):
                    if k != i:
                        buff.append(matrix[j][k])
                m.append(buff)
            sign *= -1
            sum += mul * determinant1(m, sign * matrix[0][i])
        return sum
def determinant(matrix):
    return determinant1(matrix,1)

矩阵余子式

def matrix_of_minors(M):
    list=[[0] * len(M)] * len(M[0])
    for i in range(len(M)):
        for j in range(len(M[0])):
            A=create_sub_matrix(M,i,j)
            d=determinant(A)
            list[i][j]+=d
    return list

单位矩阵

def identity(M):
    row=len(M)
    column=len(M[0])
    assert row == column, "Non n by n matrix, no identity matrix"
    for r in range(row):
      for c in range(column):
        M[r][ c] = 1.0 if r == c else 0.0
    return M

逆矩阵

def submatrix(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
import copy
def inverse_matrix(M):
    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
    return C

总结

练习了对矩阵的操作,加深了对矩阵的理解同时也回顾了线性代数的知识。希望对大家有帮助。

以上是关于不使用numpy完成对矩阵的操作的主要内容,如果未能解决你的问题,请参考以下文章

不使用numpy完成对矩阵的操作

Python (NumPy, SciPy),寻找矩阵的零空间

对Numpy库ndarray对象(矩阵)中的数据的访问选取操作示例积累

python/numpy/tensorflow中,对矩阵行列操作,下标是怎么回事儿?

第四十一篇 Numpy的基本操作——聚合操作

numpy 矩阵操作