numpy vectorize a function to accepts vectors of different lengths and return the tensor result

后端 未结 1 1887
失恋的感觉
失恋的感觉 2021-01-22 18:39

I want to vectorize a function f(a, b) so that, when I enter a and b as two vectors, the tensor of combinations is returned. Here is an illustrative example:

<
相关标签:
1条回答
  • 2021-01-22 19:20

    You can chain with np.ix_:

    >>> import functools
    >>> 
    >>> def tensorize(f):
    ...     fv = np.vectorize(f)
    ...     @functools.wraps(f)
    ...     def ft(*args):
    ...         return fv(*np.ix_(*map(np.ravel, args)))
    ...     return ft
    ... 
    >>> tester = tensorize(tester)
    >>> tester(np.arange(3), np.arange(2))
    array([[0., 0.],
           [0., 1.],
           [0., 4.]])
    
    0 讨论(0)
提交回复
热议问题