Radek
Radek

Reputation: 1413

Matlab's filter in Java

I am trying to implement in java Matlab's function "filter" in Java.

Y = FILTER(B,A,X)

It says that : The filter is a "Direct Form II Transposed" implementation of the standard difference equation:

 a(1)*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)

Can somebody help me with that as I don't really understand the above formula. Can somebody show me an example of the above formula using these parameters:

e.g. filter([1 -1],[1 -hpf_pole],S')

where hpf_pole = 0.98

S =

-3.26368263029463   0.598694437762099   0.925551549649237
-3.15561902947223   0.00249461257261130 2.35703360665011
-2.89398994439634   1.98384531062216    3.67478741307554

Upvotes: 2

Views: 1540

Answers (3)

Robert Werner Jansen
Robert Werner Jansen

Reputation: 21

More generally it would be something like:

public double[] filter(double[] b, double[] a, double[] x) {
    int nx = x.length;
    int na = a.length;
    int nb = b.length;

    double[] y = new double[nx];
    for (int k = 0; k < nx; k++) {
        y[k] = 0;
        for (int i = 0; i < nb; i++) {
            if (k - i >= 0 && k - i < nx) {
                y[k] += b[i] * x[k - i];
            }
        }
        for (int i = 1; i < na; i++) {
            if (k - i >= 0 && k - i < nx) {
                y[k] -= a[i] * y[k - i];
            }
        }
        if (Math.abs(a[0] - 1) > 1.e-9) {
            y[k] /= a[0];
        }

    }
    return y;
}

Upvotes: 0

Radek
Radek

Reputation: 1413

OK I implemented something in Java that looks like it is doing the job:

   public void filter(){
         double hpfPole = 0.98;
         double[] b = new double[]{1,-1};
         double[] a = new double[]{1, -hpfPole};
         double[] x = new double[]{-7.3416, -7.3416, -7.3416};
         double[] y = new double[x.length];

         for (int n = 0; n < y.length; n++) {
             if(n-1 < 0){
                 y[n] = b[0]*x[n];
             }else{
                y[n]= b[0]*x[n]+b[1]*x[n-1]-a[1]*y[n-1]; 
             }

         }


     }
Input: -7.3416, -7.3416, -7.3416
Output: -7.3416, -7.194768, -7.05087264

Upvotes: 0

Nzbuu
Nzbuu

Reputation: 5251

You can read about Direct Form II Transposed. But it's useful to read more about Direct Forms and Implementation of discrete transfer functions in general to know why it's useful and when to use it.

Upvotes: 1

Related Questions