Sam Kemp
Sam Kemp

Reputation: 5

Creating a 2D matrix in Python from the addition of every combination of 2 1D arrays

I'm trying to create a grid of numbers from two 1D arrays like as follows:

EXAMPLE
a = [10,11,12,13,14,15]
b = [1,2,3,4,5,6]

    [10] [11] [12] [13] [14] [15]
[1]  11   12   13   14   15   16
[2]  12   13   14   15   16   17
[3]  13   14   15   16   17   18
[4]  14   15   16   17   18   19
[5]  15   16   17   18   19   20
[6]  16   17   18   19   20   21

So the operator between each combination of values is '+'. Kind of the cross product between two vectors but using addition. Are there any methods in numpy or similar to do this or do I need to write my own function? Speed is of concern, memory not so much. Ultimately I'd have 8 dimensions in my addition matrix, the example above is just to explain my problem.

Upvotes: 0

Views: 101

Answers (2)

AGN Gazer
AGN Gazer

Reputation: 8378

import numpy as np
a = np.arange(1, 7)
b = np.arange(10, 16)
outer_sum = np.add.outer(a, b)

Then

In [5]: print(outer_sum)
[[11 12 13 14 15 16]
 [12 13 14 15 16 17]
 [13 14 15 16 17 18]
 [14 15 16 17 18 19]
 [15 16 17 18 19 20]
 [16 17 18 19 20 21]]

Upvotes: 1

Gozy4
Gozy4

Reputation: 484

You can do this:

import numpy as np
a = np.array([10,11,12,13,14,15])
b = np.array([1,2,3,4,5,6])

a = a*np.ones((a.size,a.size))
b = (b*np.ones((b.size,b.size))).transpose()
print(a+b)

Output:

Out[1]: 
array([[11., 12., 13., 14., 15., 16.],
       [12., 13., 14., 15., 16., 17.],
       [13., 14., 15., 16., 17., 18.],
       [14., 15., 16., 17., 18., 19.],
       [15., 16., 17., 18., 19., 20.],
       [16., 17., 18., 19., 20., 21.]])

Upvotes: 0

Related Questions