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

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.


1 Answer 1


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;
    y(i,:) = [tempSum]
    i = i+1;

See results below:



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.

  • \$\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, 2019 at 16:52

Your Answer

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

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