如何在F#中进行卷积? [英] How do I do convolution in F#?
问题描述
我希望卷积具有离散滤波器的离散信号。信号和滤波器是F#中的float序列。
我唯一能弄清楚方法的方法是两个嵌套的for循环和一个可变的数组来存储结果,但是感觉不太实用。 / p>
这是我无法执行的操作:
conv = double [len(信号)+ len(过滤器)-1]
for i = 1到len(信号)
for j = 1到len(过滤器)
conv [i + j ] = conv [i + j] + signal(i)* filter(len(filter)-j)
尝试以下功能:
让卷积信号滤波器=
[ | 0 ..数组长度信号+数组长度过滤器-1 |] |> Array.map(fun i->
[| 0 .. i |] |> Array.sum_by(fun j-> signal。[i] * filter。[Array.length filter-(i- j)-1]))
这可能不是最好的函数解决方案,但应该可以完成。我怀疑是否存在一种纯粹的功能性解决方案,但是该解决方案在速度上必须与当务之急相匹配。
希望有所帮助。 p>注意:该函数当前未经测试(尽管我已经确认可以编译)。让我知道它是否未完全应做。另外,请注意 i
和 j
变量所引用的内容与原始帖子所引用的内容不同。
I would like convolve a discrete signal with a discrete filter. The signal and filter is sequences of float in F#.
The only way I can figure out how to do it is with two nested for loops and a mutable array to store the result, but it does not feel very functional.
Here is how I would do it non-functional:
conv = double[len(signal) + len(filter) - 1]
for i = 1 to len(signal)
for j = 1 to len(filter)
conv[i + j] = conv[i + j] + signal(i) * filter(len(filter) - j)
Try this function:
let convolute signal filter =
[|0 .. Array.length signal + Array.length filter - 1|] |> Array.map (fun i ->
[|0 .. i|] |> Array.sum_by (fun j -> signal.[i] * filter.[Array.length filter - (i - j) - 1]))
It's probably not the nicest function solution, but it should do the job. I doubt there exists a purely functional solution that will match the imperative one for speed however.
Hope that helps.
Note: The function is currently untested (though I've confirmed it compiles). Let me know if it doesn't quite do what it should. Also, observe that the i
and j
variables do not refer to the same things as is your original post.
这篇关于如何在F#中进行卷积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!