<分区>
我需要用 C# 编写的低通和高通滤波器。对于这个过滤过程,我有双数组。我想如果我尝试将 matlab Butterworth 和 Chebyshev 算法转换为 c#,它会更容易。但是我在网上找不到butter.m和Chebyshev算法的代码,我也不想在我的电脑上安装matlab和信号处理工具箱。你能提供那些代码吗?谢谢..
<分区>
我需要用 C# 编写的低通和高通滤波器。对于这个过滤过程,我有双数组。我想如果我尝试将 matlab Butterworth 和 Chebyshev 算法转换为 c#,它会更容易。但是我在网上找不到butter.m和Chebyshev算法的代码,我也不想在我的电脑上安装matlab和信号处理工具箱。你能提供那些代码吗?谢谢..
最佳答案
LP and HP filter - Musicdsp.org documentation
我在我们的 sEMG 分析仪软件中用上面的半代码实现了过滤器,效果很好。
public class FilterButterworth
{
/// <summary>
/// rez amount, from sqrt(2) to ~ 0.1
/// </summary>
private readonly float resonance;
private readonly float frequency;
private readonly int sampleRate;
private readonly PassType passType;
private readonly float c, a1, a2, a3, b1, b2;
/// <summary>
/// Array of input values, latest are in front
/// </summary>
private float[] inputHistory = new float[2];
/// <summary>
/// Array of output values, latest are in front
/// </summary>
private float[] outputHistory = new float[3];
public FilterButterworth(float frequency, int sampleRate, PassType passType, float resonance)
{
this.resonance = resonance;
this.frequency = frequency;
this.sampleRate = sampleRate;
this.passType = passType;
switch (passType)
{
case PassType.Lowpass:
c = 1.0f / (float)Math.Tan(Math.PI * frequency / sampleRate);
a1 = 1.0f / (1.0f + resonance * c + c * c);
a2 = 2f * a1;
a3 = a1;
b1 = 2.0f * (1.0f - c * c) * a1;
b2 = (1.0f - resonance * c + c * c) * a1;
break;
case PassType.Highpass:
c = (float)Math.Tan(Math.PI * frequency / sampleRate);
a1 = 1.0f / (1.0f + resonance * c + c * c);
a2 = -2f * a1;
a3 = a1;
b1 = 2.0f * (c * c - 1.0f) * a1;
b2 = (1.0f - resonance * c + c * c) * a1;
break;
}
}
public enum PassType
{
Highpass,
Lowpass,
}
public void Update(float newInput)
{
float newOutput = a1 * newInput + a2 * this.inputHistory[0] + a3 * this.inputHistory[1] - b1 * this.outputHistory[0] - b2 * this.outputHistory[1];
this.inputHistory[1] = this.inputHistory[0];
this.inputHistory[0] = newInput;
this.outputHistory[2] = this.outputHistory[1];
this.outputHistory[1] = this.outputHistory[0];
this.outputHistory[0] = newOutput;
}
public float Value
{
get { return this.outputHistory[0]; }
}
}
请注意,此过滤器是为音频 DSP 目的而创建的。要创建干净的输出,您需要将共振设置为 sqrt(2)
。
关于c# - C#中的低通和高通滤波器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079526/