Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 369
Hanfei Sun Avatar asked Nov 15 '12 01:11

Hanfei Sun


1 Answers

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]])
like image 177
unutbu Avatar answered Nov 14 '22 23:11

unutbu