Forming a matrix from 2 vectors in Numpy with repetition of 1 vector

Using numpy arrays, I want to most economically create a matrix like this: given

from numpy import array
a = array(a1,a2,a3,...,an)
b = array(b1,...,bm)

      

processed by matrix M:

M = array([[a1,a2,b1,...,an],
           ...           ...,
           [a1,a2,bm,...,an]]

      

I am aware of numpy array broadcast methods, but could not find a good way. Any help would be much appreciated,

amusing, Rob

+3


source to share


2 answers


You can use numpy.resize

in a

first and then add b

elements at the required indices using numpy.insert

re-size in the array:



In [101]: a = np.arange(1, 4)

In [102]: b = np.arange(4, 6)                                           

In [103]: np.insert(np.resize(a, (b.shape[0], a.shape[0])), 2, b, axis=1)                                                                       
Out[103]: 
array([[1, 2, 4, 3],                                                    
       [1, 2, 5, 3]])  

      

+2


source


You can use a combination of functions numpy.tile

and numpy.hstack

.

M = numpy.repeat(numpy.hstack(a, b), (N,1))

      



I'm not sure I understand your target matrix.

0


source







All Articles