Home > Mobile >  Divide an array into smaller arrays, square matrix
Divide an array into smaller arrays, square matrix

Time:12-07

I am trying to reshape a matrix, but I am struggling to make reshape work

Lets say that I have a (6x6) matrix (A), and we want to divide it in 4 arrays (A1,A2,A3,A4). For example

A=[[ 1  2  3  4  5  6]
   [ 7  8  9 10 11 12]
   [13 14 15 16 17 18]
   [19 20 21 22 23 24]
   [25 26 27 28 29 30]
   [31 32 33 34 35 36]]

I want to divide it in 4 parts, such as:

A=[[ 1  2  3|  4  5  6]
   [ 7  8  9|  10 11 12]
   [13 14 15| 16 17 18]
---------------------
   [19 20 21| 22 23 24]
   [25 26 27| 28 29 30]
   [31 32 33| 34 35 36]]

such as

A1=[[ 1  2  3]
    [ 7  8  9]
    [13 14 15]]

A2=  ..

A3= ..

A4=[[22 23 24]
     28 29 30]
     34 35 36]]

Any suggestions would help me a lot!

CodePudding user response:

The smaller arrays could simply be created by slicing the bigger array.

A = np.array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12],
       [13, 14, 15, 16, 17, 18],
       [19, 20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29, 30],
       [31, 32, 33, 34, 35, 36]])
A1 = A[0:3, 0:3]
A2 = A[3:6, 0:3]
A3 = A[0:3, 3:6]
A4 = A[3:6, 3:6]

When using reshape, the new array should be compatible with the old array (the number of elements should stay the same)

  • Related