If I have an array in numpy a
which is nx 1
. In addition, I have a function F(x,y)
which takes in two values and returns a single value. I want to construct an nxn
matrix b
where b_ij = F(a_i, a_j) (in the array a
). Is there any way to do this without looping over both arrays?
Assume that your function is:
def F(a_i, a_j):
return (a_i + a_j) if a_i % 2 == 0 else (a_i + a_j + 1)
To call it on 2 arrays in 1 go, define the vectorized version of this function:
FF = np.vectorize(F)
Then call it:
result = FF(a, a.T)
As the source array I used:
a = np.array([[1], [5], [10], [50], [80]])
so its shape is (5, 1) (a single-column array) and got:
array([[ 3, 7, 12, 52, 82],
[ 7, 11, 16, 56, 86],
[ 11, 15, 20, 60, 90],
[ 51, 55, 60, 100, 130],
[ 81, 85, 90, 130, 160]])
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.