文章目录
- [1. **创建矩阵**:](#1. 创建矩阵:)
- [2. **矩阵加法**:](#2. 矩阵加法:)
- [3. **矩阵乘法**:](#3. 矩阵乘法:)
- [4. **矩阵转置**:](#4. 矩阵转置:)
- [5. **元素级操作**:](#5. 元素级操作:)
- [6. **汇总统计**:](#6. 汇总统计:)
- [7. **逻辑操作**:](#7. 逻辑操作:)
理解你的需求,我将为每个功能写一个单独的代码块来演示不同的矩阵操作。以下是单独的示例代码,每个示例都包含一个不同的矩阵操作:
1. 创建矩阵:
python
import numpy as np
# 创建矩阵
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("矩阵:")
print(matrix)
2. 矩阵加法:
python
import numpy as np
matrix1 = np.array([[1, 2, 3], [4, 5, 6]])
matrix2 = np.array([[7, 8, 9], [10, 11, 12])
result_addition = matrix1 + matrix2
print("矩阵加法结果:")
print(result_addition)
3. 矩阵乘法:
python
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8])
result_multiplication = np.dot(matrix1, matrix2)
print("矩阵乘法结果:")
print(result_multiplication)
4. 矩阵转置:
python
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6])
transposed_matrix = matrix.T
print("矩阵转置:")
print(transposed_matrix)
5. 元素级操作:
python
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6])
result_elementwise_add = matrix + 2
result_elementwise_multiply = matrix * 2
print("元素级加法结果:")
print(result_elementwise_add)
print("元素级乘法结果:")
print(result_elementwise_multiply)
6. 汇总统计:
python
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6])
row_sum = np.sum(matrix, axis=1)
column_sum = np.sum(matrix, axis=0)
print("行的求和:")
print(row_sum)
print("列的求和:")
print(column_sum)
7. 逻辑操作:
python
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6])
comparison_result = matrix > 3
selected_elements = matrix[matrix > 3]
print("逻辑操作结果:")
print(comparison_result)
print("布尔索引结果:")
print(selected_elements)
这些单独的示例代码演示了不同的矩阵操作,包括创建矩阵、矩阵加法、矩阵乘法、矩阵转置、元素级操作、汇总统计、逻辑操作等。你可以单独运行每个示例以查看其效果。