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

Form element-wise list from scalar and matrix

I have a zero-dimensional numpy scalar s and a two-dimensional numpy matrix m. I want to form a matrix of vectors in which all the elements of m are paired with s as in the following example:

import numpy as np

s = np.asarray(5)

m = np.asarray([[1,2],[3,4]])

# Result should be as follows

array([[[5, 1],
        [5, 2]],

       [[5, 3],
        [5, 4]]])

In other words, I want to vectorize the operation np.asarray([s, m]) element-wise at the lowest level of m. Is there an obvious way to do that for any multidimensional array m within numpy?

I’m sure this is somewhere, but I have trouble expressing it in words and cannot find it. If you can find it, please feel free to redirect me there.

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

>Solution :

A possible solution, which uses broadcast_to and stack functions to combine two arrays, s and m, into a single array along a new axis. The steps are:

  • First, np.broadcast_to(s, m.shape) expands the shape of array s to match that of array m without copying data.

  • Then, np.stack([np.broadcast_to(s, m.shape), m], axis=-1) joins the broadcasted s and m along a new last axis

np.stack([np.broadcast_to(s, m.shape), m], axis=-1)

Output:

array([[[5, 1],
        [5, 2]],

       [[5, 3],
        [5, 4]]])
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