Issue
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))
Solution
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
Answered By - Psidom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.