2

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

2 Answers 2

3

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

Comments

1

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]])

3 Comments

THANKS! but there's another thing also confusing me, it's kind of hard to explain, do you mind taking a look at a file ?
You're welcome! I'm off to bed, actually, but if you ask a specific separate question about your file, I'm sure someone will answer it :)
I'll just keep trying for a little longer, thanks again :),

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.