Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using numpy arrays I want to create such a matrix most economically: given

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

shall be processed to matrix M:

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

I am aware of numpy array's broadcasting methods but couldn't figure out a good way. Any help would be much appreciated,

cheers, Rob

like image 296
tee Avatar asked Dec 10 '25 00:12

tee


1 Answers

You can use numpy.resize on a first and then add b's items at the required indices using numpy.insert on the re-sized 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]])  
like image 185
Ashwini Chaudhary Avatar answered Dec 12 '25 12:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!