在 numpy 中向量化乘法累加

问题描述 投票:0回答:1

这种简单的低通滤波器算法可以使用 Python numpy 进行矢量化吗?我想在不执行显式 for 循环的情况下获取输出数组 xLP。到目前为止我发现的“乘法和累加”numpy 答案似乎并不能直接启用这种计算。

import numpy as np

f = 0.1  # low-pass filter fraction
elems = 10
x = np.random.randn(elems) # normal distribution
xLP = np.zeros(elems+1)  # starting point for output

for i in range(0,elems):
     xLP[i+1] = (1.0-f)*xLP[i] + f*x[i]
     
# now xLP contains a low-pass filtered version of x
python numpy vectorization
1个回答
0
投票

您可以创建自定义 ufunc,然后使用 np.accumulate 来执行此操作如此处所述

唯一的问题是你必须将状态变量 x0 的初始值添加到输入序列中,我在这里使用

np.concatenate
做到了:

f = 0.1

def fLP(x, u):
    return (1. - f) * x + f * u

fLP_ufunc = np.frompyfunc(fLP, nin=2, nout=1)

elems = 10
U = np.random.randn(elems)
xLP = fLP_ufunc.accumulate(np.concatenate([[0], U]))
print(xLP)

输出:

[0.0 0.012215536705072135 -0.10167816687137106 -0.1199850967608808
 -0.05981846281683581 -0.02892504449551806 -0.08952817494049874
 -0.2559176019185426 -0.20433416944559457 -0.20696107336969943
 -0.15984414263697735]
© www.soinside.com 2019 - 2024. All rights reserved.