python - 如何使用python从块中索引整个矩阵
问题描述
我正在尝试在 python 的 for 循环中迭代地创建一个块矩阵。有没有办法使用简单索引,其中索引对应于矩阵索引而不是标量索引。例如,将以下内容想象为块矩阵中的两个 2x2 矩阵:
4 5 6 7
1 2 3 4
有没有办法索引子矩阵,例如:
block_matrix[0,0] =
4 5
1 2
block_matrix[0,1] =
6 7
3 4
我的最终目标是有一个 for 循环来堆叠这些。例如:
for i in range(3):
for j in range(3):
mat = single_matrix
block_matrix[i,j] = mat
block_matrix =
matrix_1_1 matrix_1_2 matrix_1_3
matrix_2_1 matrix_2_2 matrix_2_3
matrix_3_1 matrix_3_2 matrix_3_3
解决方案
我相信你想要的功能numpy.reshape
是numpy.swapaxes
https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html
import numpy as np
a = np.array([[4,5,6,7],[1,2,3,4]])
b = np.reshape(a, (2,2,2), order="C")
c = np.swapaxes(b, 0, 1)
print(c)
输出:
[[[4 5]
[1 2]]
[[6 7]
[3 4]]]
编辑
这是一个适用于您的情况的版本,包括循环的作用:
import numpy as np
a = np.random.random((6,6))
b = np.reshape(a, (3,2,3,2), order="C")
c = np.swapaxes(b, 2, 1)
print(a)
print(c[0,1])
输出:
[[0.14413028 0.32553884 0.84321485 0.52101265 0.39548678 0.04210311]
[0.06844168 0.37270808 0.0523836 0.66408026 0.29857363 0.9086674 ]
[0.30052066 0.85342026 0.42354871 0.20516629 0.47962509 0.31865669]
[0.92307636 0.36024872 0.00109126 0.66277798 0.70634145 0.02647658]
[0.18408546 0.79832633 0.92462421 0.8060224 0.51464245 0.88324207]
[0.24439081 0.61620587 0.66114919 0.50045374 0.93085541 0.85732735]]
[[0.84321485 0.52101265]
[0.0523836 0.66408026]]
推荐阅读
- python - 为什么我的 Firebase Firestore 查询不在 order_by 中?
- java - org.hibernate.MappingException:无法确定类型:java.util.List for Hierarchy Ref Cursor 函数结果
- javascript - javascript中的递归和函数调用
- ruby-on-rails - bash:bundle:即使安装了捆绑器,也找不到命令
- java - 对于开发人员,GraalVM 19.3 的 CE 和 EE 版本有什么区别?
- .net-core - 在 .NET Core 2.0 中出现“无法加载文件或程序集”错误
- flutter - 如何使用 Dart/Flutter 在 Cloud Firestore 中存储一个简单的矩阵?
- javascript - 如何合并 2 个不同的对象数组并返回匹配项和不匹配项?
- java - 无法将 Excel 文件中的日期值放入 Web 应用程序表单
- c++ - 如何找到 C++ 虚假复制操作?