Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

half the dimension of a numpy array

Lets say I have a numpy array of 4×4 dimension and want to change it to 2×2 by taking its halve. So, theoretically do something like this:

enter image description here

is this possible without using any loop and for it to work on not only a 4×4 but lets say a 500×500?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#input:
x_4= np.array([[1, 2, 4, 5], [3, 4, 6, 8], [5, 3, 1, -1], [2, 3, 5, 0]])

# thinking it would work with something like this:
new = x_4[:2, :2]/4 + x_4[:2, -2:]/4 + x_4[-2:, :2]/4 + x_4[-2:, -2:]/4
new
# output: array([[11,  9],[16, 15]])

#Expected output: array([[2.5, 5.75], [3.25, 1.25]])

>Solution :

Numpy Version:

you can do a reshape and perform mean over two axis to get the desired result

import numpy as np

blocksize = 500

Mat = np.random.rand(blocksize,blocksize)

## reshape into (blocksize/2 x blocksize/2 ) 2x2 matrices

blocks = Mat.reshape(blocksize//2, 2, blocksize//2, 2)

block_mean = np.mean(blocks, axis=(1,-1))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading