首页 > 解决方案 > 如何使用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

标签: pythonmatrix

解决方案


我相信你想要的功能numpy.reshapenumpy.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]]

推荐阅读