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
.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.