4
\$\begingroup\$

I need to implement the Matlab filter(b,a,x) function in Java. Before I do this, I would like to rewrite the function in Matlab before translating into Java. So far, writing out all the coefficients works really well. See below:

x = load('data.csv');
windowSize = 10; 
b = (1/windowSize)*ones(1,windowSize); % b coefficient - a is unused 
i = 1;
for n = length(b) : length(x) % yes I know I am losing my first 10 samples
    y(i,:) = [ b(1)*x(n) + b(2)*x(n-1) + b(3)*x(n-2) + b(4)*x(n-3) + ... 
        b(5)*x(n-4) + b(6)*x(n-5) + b(7)*x(n-6) + b(8)*x(n-7) + ...
        b(9)*x(n-8) + b(10)*x(n-9) ];
    i = i+1; % used for indexing calculated results into new array
end

However, I want the loop contents to automatically update when I change the window size. In the above example, if I were to increase the windowsize by a factor of two, then I would have to write out twice as many multiples of b and x within the for loop. Which is a terrible solution to my problem. Please advise.

\$\endgroup\$
0
\$\begingroup\$

So this solution works:

x = load('data.csv');
windowSize = 10; 
b = (1/windowSize)*ones(1,windowSize);
i = 1;

for n = windowSize: length(x)
    m = 0;
    tempSum = 0;
        for j = 1 : windowSize
            temp = b(j)*x(n-m);
            tempSum = tempSum + temp;
            m = m + 1;
        end
    y(i,:) = [tempSum]
    i = i+1;
end

See results below:

windowsize10

windowsize30

Instead of having really inaccurate results in the beginning I just skip these. It's important to note that you are losing an amount of samples equal to the number of b coefficients in this solution. So make sure to rescale the X-axis.

Results were compared using Matlabs C = setdiff(y,yy) function and found no difference between the proposed solution and Matlabs filter(b,a,x) function.

\$\endgroup\$
  • \$\begingroup\$ There are much better ans simpler ways to implement Box Filter. If this is all you need, you can get much better. \$\endgroup\$ – Royi Feb 8 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.