numpynumpy-ndarrayarray-broadcasting

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.


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:

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

    Output:

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