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