简体   繁体   中英

How to use numpy to add any two elements in an array and produce a matrix?

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM