How can I write the Matlab “filter”-function myself?

后端 未结 5 1805
攒了一身酷
攒了一身酷 2021-02-06 19:23

I would like to use a Butterworth filter on a 1D-Signal. In Matlab the script would look like this:

 f=100;
 f_cutoff = 20; 
 fnorm =f_cutoff/(f/2);
 [b,a] = but         


        
5条回答
  •  生来不讨喜
    2021-02-06 19:46

    I implemented filter function used by Matlab in Java :

    The filter function is implemented as a direct form II transposed structure,

    y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb) - a(2)*y(n-1) - ... - a(na+1)*y(n-na)

    where n-1 is the filter order, which handles both FIR and IIR filters [1], na is the feedback filter order, and nb is the feedforward filter order.

    public void filter(double [] b,double [] a, ArrayList inputVector,ArrayList outputVector){
            double rOutputY = 0.0;    
            int j = 0;
            for (int i = 0; i < inputVector.size(); i++) {
                if(j < b.length){
                    rOutputY += b[j]*inputVector.get(inputVector.size() - i - 1);
                }
                j++;
            }
            j = 1;
            for (int i = 0; i < outputVector.size(); i++) {
                if(j < a.length){
                    rOutputY -= a[j]*outputVector.get(outputVector.size() - i - 1);
                }
                j++;   
            }
            outputVector.add(rOutputY);
        }
    

    and Here is an example :

    ArrayListinputVector = new ArrayList();
    ArrayListoutputVector = new ArrayList();
    double [] a = new double [] {1.0000,-3.518576748255174,4.687508888099475,-2.809828793526308,0.641351538057564};
    double [] b = new double [] { 0.020083365564211,0,-0.040166731128422,0,0.020083365564211};
    double  []input = new double[]{1,2,3,4,5,6,7,8,9};
    for (int i = 0; i < input.length; i++) {
        inputVector.add(input[i]);
        filter(b, a, inputVector, outputVector);
    }
    System.out.println(outputVector);
    

    and output was :

    [0.020083365564211, 0.11083159422936348, 0.31591188140651166, 0.6484669362153569, 1.099378239134486, 1.6451284697769086, 2.254636012320566, 2.894724888960297, 3.534126758562545]
    

    as in Matlab output

    That's it

提交回复
热议问题