7.调用numpy库实现矩阵的加、减、乘、数乘、方阵,求逆,求行列式, 已知A,B,C三个矩阵,编写代码,请将(1)-(4)结果输出到屏幕
时间: 2023-11-29 14:05:38 浏览: 78
基于numpy等python实现的基础库实现机器学习经典算法+源代码+文档说明
好的,以下是你要的代码:
```python
import numpy as np
# 定义矩阵A
A = np.array([[1, 2], [3, 4]])
# 定义矩阵B
B = np.array([[5, 6], [7, 8]])
# 定义矩阵C
C = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# (1)矩阵加法
print("A + B = \n", A + B)
# (2)矩阵减法
print("A - B = \n", A - B)
# (3)矩阵乘法
print("A * B = \n", np.dot(A, B))
# (4)数乘
print("2 * A = \n", 2 * A)
# (5)方阵
D = np.array([[1, 2], [3, 4]])
print("D = \n", D)
print("D的逆矩阵 = \n", np.linalg.inv(D))
print("D的行列式 = ", np.linalg.det(D))
```
输出结果为:
```
A + B =
[[ 6 8]
[10 12]]
A - B =
[[-4 -4]
[-4 -4]]
A * B =
[[19 22]
[43 50]]
2 * A =
[[2 4]
[6 8]]
D =
[[1 2]
[3 4]]
D的逆矩阵 =
[[-2. 1. ]
[ 1.5 -0.5]]
D的行列式 = -2.0000000000000004
```
阅读全文