%% Apply Lowpass Filter to Input Signal
% Assuming a sample rate of 20 kHz, create a fourth-order Butterworth filter with a 3-dB frequency of 2.5 kHz. Filter coefficients for butter must be constants for code generation.

type ButterFilt

%
% Use the Butterworth filter to lowpass-filter a noisy sine wave. Plot the result.

t = transpose(linspace(0,pi,10000));
x = sin(t) + 0.03*randn(numel(t),1);

% Filter the noisy sine wave using the Butterworth filter.

fx = ButterFilt(x);
plot(fx)

%
% Run the codegen command to obtain the C source code ButterFilt.c and MEX file:

codegen ButterFilt -args {zeros(10000,1)} -o ButterFilt_mex -report

%
% The C source code includes the five numerator and denominator coefficients of the fourth-order Butterworth filter as static constants. Apply the filter using the MEX-file:

output_data = ButterFilt_mex(x);
hold on
plot(output_data)
hold off

% Copyright 2018 The MathWorks, Inc.