Poor MEX performance when running filtfilt

4 views (last 30 days)
Diogo Tecelão
Diogo Tecelão on 28 Nov 2020
Answered: Jan on 11 Dec 2020
Hi all,
I'm currently on the journey of converting my MATLAB data processing script into C. While testing some part of it (filtering data using filtfilt), I noticed that running the generated MEX file is MUCH slower than running the MATLAB function directly.
This is my MATLAB function:
function filter_test(data)
% Initialise filtered data
f_data = data;
% Set the filter coeficients to remove the 50Hz and its harmonics
filter_coeficients = struct();
filter_coeficients.coef_50Hz = [...]; %1x4467 double
filter_coeficients.coef_100Hz = [...]; %1x4467 double
filter_coeficients.coef_150Hz = [...]; %1x4467 double
filter_coeficients.coef_200Hz = [...]; %1x4467 double
filter_coeficients.coef_250Hz = [...]; %1x4467 double
filter_coeficients.coef_300Hz = [...]; %1x4467 double
filter_coeficients.coef_350Hz = [...]; %1x4467 double
filter_coeficients.coef_400Hz = [...]; %1x4467 double
filter_coeficients.coef_450Hz = [...]; %1x4467 double
% Apply all the filters
filter_coeficients_id = fieldnames(filter_coeficients);
for c=1:numel(filter_coeficients_id)
f_data = filtfilt(filter_coeficients.(filter_coeficients_id{c}), 1, f_data);
I generated the MEX file (.mexw64) with the following command:
codegen('filter_test', '-args', {coder.typeof(double(0), [Inf Inf])})
This was one of the test I made:
data = rand(30000,1);
filter_test(data); % Elapsed time is 1.914894 seconds.
filter_test_mex(data); % Elapsed time is 492.794533 seconds.
The difference is abysmal! Forcing the code to coder.inline('always') made this even worse, as the run time reaches 997.7 seconds.
Am I doing something wrong? I guess the C performance will be similar to the MEX performance? Why is the MEX so slow when compared to MATLAB?
Wilson A N
Wilson A N on 11 Dec 2020
Hi Diogo,
I tried using some random filter coefficients to try and reproduce the issue but I was not able to observe the slowdown you had reported. Below are my results:
MATLAB Simulation time is
MEX Simulation time is
SIL Simulation time is
(SIL simulation is actually checking lib/dll time)
Please update the MATLAB Release in which you are facing the issue along with the filter coefficients. This will help us to look into the issue further.

Sign in to comment.

Answers (1)

Jan on 11 Dec 2020
Just a remark: With FiltFiltM (https://www.mathworks.com/matlabcentral/fileexchange/32261-filterm ) my Matlab 2018b needs 6.0 instead of 8.0 seconds as for filtfilt.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by