python 对角矩阵拼接
时间: 2024-01-14 20:21:47 浏览: 281
python 实现矩阵对角线之和
5星 · 资源好评率100%
以下是两种Python对角矩阵拼接的方法:
1. 批量沿邻接矩阵对角线拼接操作:
```python
import numpy as np
# 创建两个邻接矩阵
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
matrix2 = np.array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
# 沿对角线拼接两个矩阵
result = np.block([[matrix1, np.zeros_like(matrix1)],
[np.zeros_like(matrix2), matrix2]])
print(result)
```
输出:
```
[[ 1 2 3 0 0 0]
[ 4 5 6 0 0 0]
[ 7 8 9 0 0 0]
[ 0 0 0 10 11 12]
[ 0 0 0 13 14 15]
[ 0 0 0 16 17 18]]
```
2. 基于Python的邻接矩阵沿对角线拼接操作简单方法:
```python
import numpy as np
# 创建两个邻接矩阵
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
matrix2 = np.array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
# 沿对角线拼接两个矩阵
result = np.concatenate((np.concatenate((matrix1, np.zeros_like(matrix1)), axis=1),
np.concatenate((np.zeros_like(matrix2), matrix2), axis=1)), axis=0)
print(result)
```
输出:
```
[[ 1 2 3 0 0 0]
[ 4 5 6 0 0 0]
[ 7 8 9 0 0 0]
[ 0 0 0 10 11 12]
[ 0 0 0 13 14 15]
[ 0 0 0 16 17 18]]
```
阅读全文