简体   繁体   中英

How to index whole matrix from block with python

I am attempting to iteratively create a block matrix within a for loop in python. Is there a way to use simple indexing in which the index corresponds to the matrix index instead of a scalar index. For example, imagine the following as two 2x2 matrices in a block matrix:

4 5 6 7
1 2 3 4

Is there a way to index the sub-matrices such that:

block_matrix[0,0] = 
4 5
1 2

block_matrix[0,1] = 
6 7
3 4

My end goal is to have a for loop to stack these. For example:

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

I believe the functions you want are numpy.reshape and 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]]]

Edit

Here is a version that should work for your case, including what the loop does:

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

Using numpy with slicing would be one good way to 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 

There, of course I just created a simple matrix of shape (3,3) and used it for all sub-parts of block_matrix but I hope you get the gist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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