1

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.

2 Answers 2

2

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]]])
Sign up to request clarification or add additional context in comments.

Comments

0

The stack is fine. But since s needs to be repeated, a good alternative is to create a zero array of the desired shape, and allow broadcasting to fill in the columns:

In [2]: s = np.asarray(5)
   ...: 
   ...: m = np.asarray([[1,2],[3,4]])

In [3]: res = np.zeros((m.shape)+(2,)); res
Out[3]: 
array([[[0., 0.],
        [0., 0.]],

       [[0., 0.],
        [0., 0.]]])

In [4]: res[:,:,0] = s; res[:,:,1] = m

In [5]: res
Out[5]: 
array([[[5., 1.],
        [5., 2.]],

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.