How can I calculate an outer function in python?

后端 未结 3 2079
醉酒成梦
醉酒成梦 2021-01-07 06:18

If I have a random function like func(x,y) = cos(x) + sen(y) + x*y how can I apply it to all the pairs of elements in 2 arrays?

I found https://docs.scipy.org/doc/nu

3条回答
  •  执念已碎
    2021-01-07 06:44

    One way to solve this is broadcasting:

    import numpy as np
    
    def func(x, y):
        x, y = np.asarray(x)[:, None], np.asarray(y)
        return np.cos(x) + np.sin(y) + x*y
    

    The [:, None] adds another dimension to an array and therefor triggers NumPys broadcasting.

    >>> func([1,2], [3,4])
    array([[ 3.68142231,  3.78349981],
           [ 5.72497317,  6.82705067]])
    

提交回复
热议问题