Reputation: 19
I have to 1d arrays
x = [1,2,3,4,5]
y = [5,6,7,8,9]
and a zero 2d array
2d_array=np.zeros((5, 5))
I have this equation : 50*x + 20*y
I want to make a loop to find all possible answers from x and y and store them in the 2d_array
[0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0]
so this should be
[50*x[0]+20*y[0],50*x[1]+20*y[0],50*x[2]+20*y[0],50*x[3]+20*y[0],50*x[4]+20*y[0]
50*x[0]+20*y[1],50*x[1]+20*y[1]50*x[2]+20*y[1],50*x[3]+20*y[1],50*x[4]+20*y[1].......
And so on, I'm not sure if the explanation is clear, but if it is not tell me and I'll upload the actual file of the problem.
Thanks
Upvotes: 2
Views: 1145
Reputation: 164613
You can perform your calculation in a vectorised fashion:
x = np.array([1,2,3,4,5])
y = np.array([5,6,7,8,9])
res = 50*x + 20*y[:, None]
array([[150, 200, 250, 300, 350],
[170, 220, 270, 320, 370],
[190, 240, 290, 340, 390],
[210, 260, 310, 360, 410],
[230, 280, 330, 380, 430]])
Here, the indexer [:, None]
change the shape of y
from (1,)
to (5, 1)
. Broadcasting then allows creation of a 2d array result.
You can expect a performance improvement versus a method based on list comprehension, although you may only notice this for larger input arrays:
%timeit 50*x + 20*y[:, None] # 10.1 µs
%timeit np.array([x_*50+y_*20 for y_ in y for x_ in x]).reshape(5,5) # 30.2 µs
Upvotes: 3
Reputation: 51335
You don't need to pre-make the 2-d array, and you can do it all in this list comprehension:
np.array([x_*50+y_*20 for y_ in y for x_ in x]).reshape(5,5)
Which returns:
array([[150, 200, 250, 300, 350],
[170, 220, 270, 320, 370],
[190, 240, 290, 340, 390],
[210, 260, 310, 360, 410],
[230, 280, 330, 380, 430]])
Upvotes: 1