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

Apply numpy broadcast_to on each vector in an array

I want to apply something like this:

a = np.array([1,2,3])
np.broadcast_to(a, (3,3))

array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

On each vector in a multi-vector array:

a = np.array([[1,2,3], [4,5,6]])
np.broadcast_to(a, (2,3,3))

ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,3)  and requested shape (2,3,3)

To get something like this:

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

array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],

       [[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]]])

>Solution :

One way is to use list-comprehension and broadcast each of the inner array:

>>> np.array([np.broadcast_to(i, (3,3)) for i in a])

array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],
       [[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]]])

Or, you can just add an extra dimension to a then call broadcast_to over it:

>>> np.broadcast_to(a[:,None], (2,3,3))

array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],
       [[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]]])
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