Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add the values of two arrays with different dimensions together

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading