12-矩阵2_相加

  • 阅读: 162
  • 更新: 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
import random


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


def jz_add(jz1, jz2):
    """矩阵相加"""
    row_len = len(jz1)
    col_len = len(jz1[0])
    jz3 = []
    for i in range(row_len):
        jz3.append([0]*col_len)
        for j in range(col_len):
            jz3[i][j] = jz1[i][j] + jz2[i][j]
    return jz3


jz1 = new_jz()
jz2 = new_jz()
jz3 = jz_add(jz1, jz2)

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

4. 运行示例

1
2
3
矩阵1为:[[9, 8, -4], [-2, 4, -1]]
矩阵2为:[[4, -5, 1], [-8, -3, 6]]
两者之和为:[[13, 3, -3], [-10, 1, 5]]

5. 进阶思考

  1. 矩阵相加函数中加入俩矩阵是否是同型矩阵

=== 全文完 ===


欢迎加入QQ群:778391413

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