Search code examples
pythonpython-3.xmatrixjpegdct

Creating 8x8 matrices out of a bigger matrix


I currently have a 170x296 matrix and need to divide it into 8x8 matrices. Any Idea on how to do that?

[1 , 2 , 3 , 4 , ...  , 170]    --> 296x170 matrix 
[171 , ...                 ]
[342 , ...                 ]
[...                       ]
[49900 ...                 ]

and I want to convert it into:

 [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8                ]
 [171 , 172 , 173 , 174 , 175 , 176 , 177 , 178]
 [...                                          ]


[9 , 10 , 11 , 12 , 13 , 14 , 15 , 16        ]
[179, 180 , 181 , 182 , 183 , 184 , 185 , 186]
[...                                         ]

and so on.

(In this case, it's a 170x296 matrix, so not all of the values would fit in 8x8 matrices. The last few values that wouldn't fit can be stored in a list.)

Thanks on beforehand!


Solution

  • Here is one possible solution using some test identity matrix. Using flatten, you convert you big single matrix into 1-d array and then simply loop over the elements in sub-groups of 64 and convert them back to 8x8 submatrices and save them into some list if you want to store them. You just need one for loop. The remaining elements that doesn't make a matrix can be stored in a list using the % modulus operator and index slicing [-length%64:]

    a = np.eye(170, 296)
    a_flat = a.flatten()
    length = len(a_flat)
    
    new_matrices = []
    
    for i in range(0, length, 64):
        try:
            new_matrices.append(a_flat[i:i+64].reshape((8,8)))
        except:
            break
    remaining = a_flat[-(length%64):]