繁体   English   中英

如何使用 python 从块中索引整个矩阵

[英]How to index whole matrix from block with 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.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)

Output:

[[[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])

Output:

[[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]]

使用带有切片numpy将是 go 的一种好方法。

import numpy as np
block_matrix = np.zeros((9,9))  # shape (9,9)
mat = np.reshape(np.arange(9), (3,3))  # shape (3,3)

for i in range(3):
   for j in range(3):
      block_matrix[i*3:i*3+3,j*3:j*3+3] = mat

# block_matrix = 
#         mat mat mat 
#         mat mat mat 
#         mat mat mat 

当然,我只是创建了一个简单的形状 (3,3) 矩阵,并将其用于 block_matrix 的所有子部分,但我希望你能明白要点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM