Skip to content

矩阵相乘

难度:⭐⭐

1. 题目描述

题目描述

随机两个矩阵进行相乘

2. 关键点

  • 数学矩阵概念

3. 代码实现

点击显示代码
python
import random


def new_jz(row_len=2, col_len=3):
    """随机矩阵创建函数"""
    jz = []
    for i in range(row_len):
        row = [random.randint(0, 10) for i in range(col_len)]
        jz.append(row)
    return jz


def jz_multiply(jz1, jz2):
    """矩阵相乘"""
    jz1_row_len = len(jz1)
    jz1_col_len = len(jz1[0])
    jz2_row_len = len(jz2)
    jz2_col_len = len(jz2[0])
    if jz1_col_len != jz2_row_len:
        raise Exception('第一个矩阵的列数不等于第二个矩阵的行数;无法相乘')
    jz3 = []
    for i in range(jz1_row_len):
        jz3.append([0]*jz2_col_len)
        for ii in range(jz2_col_len):
            _sum = 0
            for j in range(jz2_row_len):
                _sum += jz1[i][j] * jz2[j][ii]
            jz3[i][ii] = _sum
    return jz3


jz1 = new_jz(2, 3)
jz2 = new_jz(3, 2)
# jz1 = [[1, 0, 2], [-1, 3, 1]]
# jz2 = [[3, 1], [2, 1], [1, 0]]
jz3 = jz_multiply(jz1, jz2)

print(f'矩阵1为:{jz1}')
print(f'矩阵2为:{jz2}')
print(f'两者相乘为:{jz3}')

4. 运行示例

txt
矩阵1为:[[6, 3, 1], [0, 10, 2]]
矩阵2为:[[7, 8], [5, 4], [8, 10]]
两者相乘为:[[65, 70], [66, 60]]

5. 进阶思考

  1. 优化代码