如何在给定两个array_like操作数的情况下使ufunc输出矩阵(而不是尝试广播它们)?

时间:2018-10-07 16:32:11

标签: python numpy scipy numpy-ufunc

我想从ndarray得到给定两个ufunc的值矩阵,例如:

degs = numpy.array(range(5))
pnts = numpy.array([0.0, 0.1, 0.2])
values = scipy.special.eval_chebyt(degs, pnts)

上面的代码不起作用(它给出一个ValueError,因为它试图广播两个数组,但由于它们具有不同的形状而失败了:(5,)和(3,)));我想获得一个值矩阵,其中行对应于度,而列对应于要评估多项式的​​点(反之亦然,没关系)。

目前,我的解决方法只是使用for-循环:

values = numpy.zeros((5,3))
for j in range(5):
    values[j] = scipy.special.eval_chebyt(j, pnts)

有没有办法做到这一点?通常,如果您有ufunc个类似array_like的参数,如何让n知道您想要一个n维数组?

我了解numpy.vectorize,但是这似乎比简单的for循环既快又优雅(而且我甚至不确定您是否可以将其应用于现有的{{1} }。

更新那接收三个或更多参数的ufunc呢?尝试使用ufunc方法会得到outer。例如,ValueError: outer product only supported for binary functions

2 个答案:

答案 0 :(得分:3)

您所需要的正是ufuncs的outer方法:

  

ufunc.outer(A,B,** kwargs)

  Apply the ufunc op to all pairs (a, b) with a in A and b in B.
values = scipy.special.eval_chebyt.outer(degs, pnts)
#array([[ 1.    ,  1.    ,  1.    ],
#      [ 0.    ,  0.1   ,  0.2   ],
#      [-1.    , -0.98  , -0.92  ],
#      [-0.    , -0.296 , -0.568 ],
#      [ 1.    ,  0.9208,  0.6928]])

更新

有关更多参数,您必须手动广播。 meshgrid通常会对此有所帮助,将维度中的每个参数都包含在内。例如:

n=3
alpha = numpy.array(range(5))
beta =  numpy.array(range(3))
x = numpy.array(range(2))

data = numpy.meshgrid(n,alpha,beta,x)
values = scipy.special.eval_jacobi(*data)

答案 1 :(得分:1)

重塑broadcasting的输入参数。在这种情况下,将degs的形状更改为(5,1)而不是(5,)。以形状(3,)广播的形状(5,1)产生形状(5,3):

In [185]: import numpy as np

In [186]: import scipy.special

In [187]: degs = np.arange(5).reshape(-1, 1)  # degs has shape (5, 1)

In [188]: pnts = np.array([0.0, 0.1, 0.2])

In [189]: values = scipy.special.eval_chebyt(degs, pnts)

In [190]: values
Out[190]: 
array([[ 1.    ,  1.    ,  1.    ],
       [ 0.    ,  0.1   ,  0.2   ],
       [-1.    , -0.98  , -0.92  ],
       [-0.    , -0.296 , -0.568 ],
       [ 1.    ,  0.9208,  0.6928]])