Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: looping through values of two vectors [duplicate]

Say I have two vectors:

A=linspace(-2,0,6)
B=linspace(0,2,6)

and I want to create a 2-dimensional matrix (of size 2 by 36) that matches all values in A to all values in B, so it would be something like:

[[-2 , 0]
[-2 , 0.4]
[-2 , 0.8]
[-2 , 1.2]
[-2 , 1.6]
[-2 , 2.0]
[-1.6 , 0]
[-1.6 , 0.4]
[-1.6 , 0.8]
....
....
[0 , 2.0]]

I guessing I would need some kind of for loop, but I'm not entirely sure on how to do this...

like image 356
userk Avatar asked Jun 10 '26 06:06

userk


1 Answers

>>> a = np.linspace(-2, 0, 6)
>>> b = np.linspace(0, 2, 6)
>>> 
>>> out = np.empty((len(a), len(b), 2))
>>> out[..., 0] = a[:, None]
>>> out[..., 1] = b[None, :]
>>> out = out.reshape(-1, 2)
>>> out
array([[-2. ,  0. ],
       [-2. ,  0.4],
       [-2. ,  0.8],
       [-2. ,  1.2],
       [-2. ,  1.6],
       [-2. ,  2. ],
       [-1.6,  0. ],
       [-1.6,  0.4],
       [-1.6,  0.8],
       [-1.6,  1.2],
       [-1.6,  1.6],
       [-1.6,  2. ],
       [-1.2,  0. ],
       [-1.2,  0.4],
       [-1.2,  0.8],
       [-1.2,  1.2],
       [-1.2,  1.6],
       [-1.2,  2. ],
       [-0.8,  0. ],
       [-0.8,  0.4],
       [-0.8,  0.8],
       [-0.8,  1.2],
       [-0.8,  1.6],
       [-0.8,  2. ],
       [-0.4,  0. ],
       [-0.4,  0.4],
       [-0.4,  0.8],
       [-0.4,  1.2],
       [-0.4,  1.6],
       [-0.4,  2. ],
       [ 0. ,  0. ],
       [ 0. ,  0.4],
       [ 0. ,  0.8],
       [ 0. ,  1.2],
       [ 0. ,  1.6],
       [ 0. ,  2. ]])
like image 82
Jaime Avatar answered Jun 11 '26 20:06

Jaime



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!