5

The native python codes are like this:

>>> a=[1,2,3,4,5,6]
>>> [[i+j for i in a] for j in a]
[[2, 3, 4, 5, 6, 7], 
 [3, 4, 5, 6, 7, 8], 
 [4, 5, 6, 7, 8, 9], 
 [5, 6, 7, 8, 9, 10], 
 [6, 7, 8, 9, 10, 11], 
 [7, 8, 9, 10, 11, 12]]

However, I have to use numpy to do this job as the array is very large. Does anyone have ideas about how to do the same work in numpy?

1 Answer 1

9

Many NumPy binary operators have an outer method which can be used to form the equivalent of a multiplication (or in this case, addition) table:

In [260]: import numpy as np
In [255]: a = np.arange(1,7)

In [256]: a
Out[256]: array([1, 2, 3, 4, 5, 6])

In [259]: np.add.outer(a,a)
Out[259]: 
array([[ 2,  3,  4,  5,  6,  7],
       [ 3,  4,  5,  6,  7,  8],
       [ 4,  5,  6,  7,  8,  9],
       [ 5,  6,  7,  8,  9, 10],
       [ 6,  7,  8,  9, 10, 11],
       [ 7,  8,  9, 10, 11, 12]])
Sign up to request clarification or add additional context in comments.

Comments

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.