Clear Filters
Clear Filters

Code error in MATLAB function block.

1 view (last 30 days)
saleh shlimet
saleh shlimet on 1 May 2022
Commented: saleh shlimet on 2 May 2022
I wrote a code in a MATLAB function block that consists of two inputs one input for the signal that needs to be filtered and the second input for a variable cutoff frequency (Fc), as shown below but an error occurrs with the variable y (Consider preinitializing the output variable with a known type).
function y = fcn(u,Fc)
coder.extrinsic('lowpass')
% All frequency values are in Hz.
Fs = 100; % Sampling Frequency
N = 4; % Order
%Fc cut off freq
y = lowpass(u,'butter', N, Fc, Fs);

Answers (1)

Walter Roberson
Walter Roberson on 1 May 2022
Insert
y = zeros(size(u));
before the call to lowpass()
  5 Comments
Walter Roberson
Walter Roberson on 2 May 2022
Your parameters for lowpass() are wrong.
  • The passband frequency and sampling frequency go before any of the name/value pairs
  • 'butter' is not a valid option for filter()
In MATLAB, you do not construct a butterworth filter using lowpass() as a call. Instead you call butter() to generate coefficients, and then you use filter()
However... filter() expects to be passed a vector of signal values, not one sample at a time. In order to process one sample at a time, you would need to record the coefficient history output of filter(), and pass that in to the next call to filter() that processed one more sample. You would need to use persistent variables (or a "memory store") to record that history. This all is not going to be efficient.
You should instead be using Simulink blocks to do filtering. See
saleh shlimet
saleh shlimet on 2 May 2022
Thank you very much Walter for your explanation. In the digital filter design block when you double click on it you will find the parameter Fc (cutoff frequency). In my application, this parameter is variable and suppose there is code written in the MATLAB function block to generate the Fc, so the output of the MATLAB function block is Fc. How can I update this parameter in the filter block when the code generates a new value of Fc?

Sign in to comment.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!