矩阵运算

78 2024-06-29 15:20

 二阶矩阵求逆阵:

import numpy as np


def inverse_matrix(matrix):
    B = np.array([['d', '-b'], ['-c', 'a']])
    return B


# 测试
A = np.array([['a', 'b'], ['c', 'd']])
inv_A = inverse_matrix(A)

# 用python写一个求逆矩阵的函数
if inv_A is not None:
    print("原矩阵 A:")
    print(A)
    for i in range(A.shape[0]):
        for j in range(A.shape[1]):
            print("A[{}]][{}]={}".format(i+1, j+1, A[i][j]))

    print("逆矩阵 (A 的逆):")
    print(inv_A)

 

矩阵相乘

import numpy as np


def matrix_multiply(A, B):
    result = np.zeros((A.shape[0], B.shape[1]))
    # 使用三重嵌套的 for 循环来模拟矩阵相乘的操作
    for i in range(A.shape[0]):
        for j in range(B.shape[1]):
            for k in range(A.shape[1]):
                result[i][j] += A[i][k] * B[k][j]
    return result


# 定义两个矩阵 A 和 B
A = np.array([[1, 2, 3],
              [4, 5, 6]])

B = np.array([[7, 8],
              [9, 10],
              [11, 12]])

# 通过 for 循环实现矩阵相乘
C = matrix_multiply(A, B)

# 打印结果
# 用for循环模拟矩阵相乘
print("矩阵 A:")
print(A)
print("矩阵 B:")
print(B)
print("矩阵相乘结果 C:")
print(C)

 

代数余子式求逆矩阵

import numpy as np


def determinant(matrix):
    # 计算矩阵的行列式
    return np.linalg.det(matrix)


def cofactor_matrix(matrix):
    # 计算代数余子式矩阵
    cofactors = np.zeros(matrix.shape)
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            minor = np.delete(np.delete(matrix, i, axis=0), j, axis=1)
            cofactors[i, j] = ((-1) ** (i + j)) * np.linalg.det(minor)
    return cofactors


def inverse_matrix(matrix):
    # 求逆矩阵
    det = determinant(matrix)
    if det == 0:
        print("Error: The matrix is singular and cannot be inverted.")
        return None
    else:
        cofactors = cofactor_matrix(matrix)
        adjoint = cofactors.T
        inv_matrix = adjoint / det
        return inv_matrix


# 测试
A = np.array([[1, 2], [3, 4]])
inv_A = inverse_matrix(A)

# 用代数余子式求逆矩阵
if inv_A is not None:
    print("原矩阵 A:")
    print(A)
    print("逆矩阵 A 的逆:")
    print(inv_A)

 

全部评论

·