我在 python 中有一个函数,用于对标量输入进行运算,但在此过程中乘以矩阵。具体代码如下所示:
def f(t, n):
T = np.pi
a_0 = 0.5
n = np.arange(1, n + 1)
# Calculate the Fourier series of f(t)
a_n = np.sin(n*T) / (n * np.pi)
b_n = (1 - np.cos(n * T)) / (n * np.pi)
res = a_0 + np.sum(a_n * np.cos(n*t)) + np.sum(b_n * np.sin(n*t))
return res
现在,我希望它对输入向量 t 进行操作,并使实现保持向量化(不使用 for 循环)。我可以看到制作维度矩阵 len(t) x n
其中初始向量 n 只是垂直堆叠 len(t) 次,然后与 t 执行元素乘法将是一个解决方案,但是什么是实现此功能的正确方法吗?
最佳答案
这是一种向量化方法,它使用 broadcasting
接受输入向量作为 t
和使用 np.dot
矩阵乘法的最后一步的总和减少-
def f_vectorized(t, n): # where t is an array
t2D = t[:,None]
T = np.pi
a_0 = 0.5
n = np.arange(1, n + 1)
a_n = np.sin(n*T) / (n * np.pi)
b_n = (1 - np.cos(n * T)) / (n * np.pi)
nt2D = n*t2D
return a_0 + np.cos(nt2D).dot(a_n) + np.sin(nt2D).dot(b_n)
sample 运行-
In [142]: t
Out[142]: array([8, 1, 8, 0, 2, 7, 8, 8])
In [143]: n = 5
In [144]: f_vectorized(t,n)
Out[144]:
array([ 1.03254608, 0.94354963, 1.03254608, 0.5 , 0.95031599,
1.04127659, 1.03254608, 1.03254608])
关于python - 使用 NumPy 在 Python 中的数组上运行矢量化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516065/