12-矩阵3_相乘

  • 阅读: 180
  • 更新: 2022-06-11

难度:

1. 题目描述

2. 关键点

  • 数学矩阵概念

3. 代码实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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. 运行示例

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

5. 进阶思考

  1. 优化代码

=== 全文完 ===


欢迎加入QQ群:778391413

京公网安备 11011302003970号 京ICP备2022012301号-1