Home > Software engineering >  Add the values of two arrays with different dimensions together
Add the values of two arrays with different dimensions together

Time:10-18

I'm not sure if this is mathematically possible, but I'd figure I'd ask anyway.

I have two arrays with sizes (50,1) and (693,1). What I want to do is add these values together each time. In other words, I want to take the values in the first array (50,1) and add it to each of the values in the array size (693,1). Is there a way to do this in python? Every thing I've tried fails because of the different sizes of the arrays.

EDIT

Here's a short example of what I was thinking:

array_1 = [1,1,4,5]
array_2 = [1,3,4]

new_array = [2, 2, 5, 6, 4, 4, 7, 8, 5, 5, 8, 9]

So taking each of the elements in array_2 and adding them to each element of array_1

CodePudding user response:

Broadcast, sum, and flatten:

array_1 = np.array([1,1,4,5])
array_2 = np.array([1,3,4])

out = (array_1 array_2[:,None]).ravel()

Or:

out = np.add.outer(array_2, array_1).ravel()

output: array([2, 2, 5, 6, 4, 4, 7, 8, 5, 5, 8, 9])

  • Related