The error you are encountering arises because the ‘tf’ class is not supported for code generation inside a MATLAB Function block. In your code:
you are attempting to create a transfer function object within a MATLAB function block that has ‘#codegen’ enabled. However, classes such as ‘tf’, ‘ss’, and ‘zpk’ are not compatible with code generation, which is required in MATLAB function blocks used in Simulink.
A workaround would be to use the ‘coder.extrinsic’. If you only need to use the ‘tf’ function for simulation and visualization within MATLAB, and do not plan to generate code, you can declare it as an extrinsic using ‘coder.exntrinsic’. This basically tells MATLAB to call the function in the MATLAB interpreter instead of generating C/C++ code for it.
Below is the minimal example for this workaround:
coder.extrinsic('tf', 'plot');
sys = tf([1 2], [3 5 8]);
Again, this will only work during simulation inside MATLAB. It is not compatible with embedded code generation.
Another workaround would be to use Simulink Blocks. If you need a solution that works with code generation, such as for deployment to real-time systems, you should avoid using ‘tf’ altogether in MATLAB Function blocks. Instead, you can:
- Use the Transfer Function block from the Simulink > Continuous library to model transfer functions directly in Simulink.
- Alternatively, implement the system dynamics using numerical methods or state-space equations within the MATLAB Function block using only scalar operations and supported functions.
You can find additional information about ‘coder.extrinsic’ and Transfer Function Block in the official documentation of MATLAB
I hope this is helpful.