Example:
Let
JavaScript
x
3
1
A = np.array([1,2,3,5,7])
2
B = np.array([11,13,17,19,23])
3
and I would like to create a matrix C
of size (5,5)
whose elements are
JavaScript
1
2
1
c_ij = f(a[i],b[j])
2
where f
is a fixed function for example f(x,y) = x*y + x + y
which means
JavaScript
1
2
1
c_ij = a[i]*b[j] + a[i] + b[j]
2
In the case where c_ij
depends on i
and j
only and does not depend on the lists A
and B
, we can use np.fromfunction(lambda i,j: f(i,j), (5,5))
but it’s not the case.
I would like to know how we can do that ?
Advertisement
Answer
Is this what you want:
JavaScript
1
8
1
def bar(arr1, arr2, func):
2
ind1, ind2 = np.meshgrid(range(len(arr1)), range(len(arr2)))
3
x = arr1[ind1]
4
y = arr2[ind2]
5
return func(x, y)
6
7
bar(A, B, f)
8