简体   繁体   English

脾气暴躁的“双重”广播-有可能吗?

[英]Numpy “double”-broadcasting - is it possible?

Is it possible to use "double"-broadcasting to remove the loop in the following code? 是否可以使用“双重”广播删除以下代码中的循环? In other words, to broadcast across the entire time array T as well as the same-dimensioned arrays freqs and phases . 换句话说,要在整个时间数组T以及相同尺寸的数组freqsphases之间进行广播。

freqs = np.arange(100)
phases = np.random.randn(len(freqs))
T = np.arange(0, 500)

signal = np.zeros(len(T))
for i in xrange(len(signal)):
    signal[i] = np.sum(np.cos(freqs*T[i] + phases))

You can reshape T as a 2d array by adding a new axis to it, which will trigger the broadcasting when multiplied/added with a 1d array, and then later on use numpy.sum to collapse this axis: 您可以通过向T添加新轴来将T重塑为2d数组,当与1d数组相乘/相加时将触发广播,然后稍后使用numpy.sum折叠此轴:

np.sum(np.cos(freqs * T[:,None] + phases), axis=1)
#                      add new axis        remove it with sum

Testing : 测试

(np.sum(np.cos(freqs * T[:,None] + phases), axis=1) == signal).all()
# True

One idea that just came to me (but which may be computationally expensive?) is to construct the arguments as a matrix: 我刚想到的一个想法(但是这可能在计算上昂贵吗?)是将参数构造为矩阵:

phases = phases.reshape((len(phases), 1))
argumentMatrix = np.outer(freqs, T) + phases
cosineMatrix = np.cos(argumentMatrix)
signal = np.sum(cosineMatrix, axis=0) # sum, collapsing columns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM