numpy Python:应用函数扩展矩阵行的子集

qxgroojn  于 5个月前  发布在  Python
关注(0)|答案(2)|浏览(61)

假设我有以下数组:

A = np.array([1,2,3,4])

字符串
我现在想计算以下总和:

np.cos(A[0])+np.cos(A[1])*np.sin(A[0])+np.cos(A[2])*np.sin(A[1])*np.sin(A[0])+np.cos(A[3])*np.sin(A[2])*np.sin(A[1])*np.sin(A[0])


对于一般数组,什么是有效的方法?

cyvaqqii

cyvaqqii1#

逻辑并不完全清楚,但假设你想将每个值cos乘以前一个值的sin,并将第一个值乘以最后一个值的sin,你可以roll,然后相乘并sum

(np.cos(A)*np.sin(np.roll(A, 1))).sum()

字符串

pcww981p

pcww981p2#

根据你所写的,你会得到各种因子的和,其中每个i-th因子是i-th元素的余弦和所有前面元素的西内斯的乘积。如果这是真的,你可以在下面的方式中执行一个双for循环:

np.sum([np.cos(A[i]) * np.prod([np.sin(A[j]) for j in range(i)]) for i in range(len(A))])

字符串
如果没有额外的信息,很难评估是否存在更有效的方法。
假设你有足够的RAM,一个无循环的解决方案是:

# define a sines matrix NxN
sin_matrix = np.sin(A)[None, :].repeat(10, axis=0)

# replace the sines whith 1 (neutral for the product) where index >= column
sin_matrix[np.arange(len(A))[:,None]<=np.arange(len(A))[None, :]] = 1


输出为:

np.cos(A)*sin_matrix.prod(axis=1)

相关问题