def lu(matrix: Matrix): assert matrix.row_num() == matrix.col_num( ), "matrix must be a square matrix" n = matrix.row_num() A = [matrix.row_vector(i) for i in range(n)] L = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)] for i in range(n): # 看A[i][i]位置是否可以是主元 if is_zero(A[i][i]): return None, None else: for j in range(i + 1, n): p = A[j][i] / A[i][i] A[j] = A[j] - p * A[i] L[j][i] = p return Matrix(L), Matrix([A[i].underlying_list() for i in range(n)])
from playLA.Matrix import Matrix from playLA.Vector import Vector if __name__ == '__main__': matrix = Matrix([[1, 2], [3, 4]]) print(matrix) print("矩阵的形状:{}".format(matrix.shape())) print("矩阵的行数:{},矩阵的列数:{}".format(matrix.row_num(), matrix.col_num())) print("矩阵的元素个数:{}".format(matrix.size())) print("矩阵元素:{}".format(matrix[1, 1])) print("矩阵行向量:{}".format(matrix.row_vector(1))) print("矩阵列向量:{}".format(matrix.col_vector(1))) m2 = Matrix([[2, 4], [4, 6]]) print("add:{}".format(matrix + m2)) print("sub:{}".format(matrix - m2)) print("multi:{}".format(matrix * 2)) print("rMulti:{}".format(2 * matrix)) print("div:{}".format(m2 / 2)) print("neg:{}".format(-m2)) print("零矩阵:{}".format(Matrix.zero(3, 2))) T = Matrix([[1.5, 0], [0, 2]]) p = Vector([5, 3]) print("T.dot(p) = {}".format(T.dot(p))) T2 = Matrix([[0, 4, 5], [0, 0, 3]]) print("T.dot(T2) = {}".format(T.dot(T2))) print("转置:{}".format(T2.T())) I = Matrix.identity(2)
from playLA.Matrix import Matrix if __name__ == '__main__': matrix = Matrix([[1, 3, 5], [2, 4, 6]]) print(matrix) print(matrix.shape()) print("row num = {}, col num = {}".format(matrix.row_num(), matrix.col_num())) print("matrix[0][0] = {}".format(matrix[0, 0])) matrix2 = Matrix([[3, 6, 9], [1, 4, 7]]) print("add: {}".format(matrix + matrix2)) print("sub: {}".format(matrix - matrix2)) print("{} * {} = {}".format(matrix2, 3, matrix2 * 3)) print("{} * {} = {}".format(2, matrix2, 2 * matrix2)) print("{}".format(-matrix2)) print("{}".format(Matrix.zero(2, 2))) A = Matrix([[1, 2], [3, 4]]) B = Matrix([[5, 6], [7, 8]]) print("A.dot(B) = {}".format(A.dot(B))) print("B.dot(A) = {}".format(B.dot(A))) I = Matrix.identity(3) print("单位矩阵I = {}".format(I)) print("matrix2.dot(I) = {}".format(matrix2.dot(I)))