5
\$\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.

asked Feb 23, 2018 at 13:56
\$\endgroup\$

1 Answer 1

2
\$\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.

answered Feb 24, 2018 at 16:46
\$\endgroup\$
1
  • \$\begingroup\$ There are much better ans simpler ways to implement Box Filter. If this is all you need, you can get much better. \$\endgroup\$ Commented Feb 8, 2019 at 16:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.