How to include custom code in the generated initialize function when an initialize block is already present in the model

How can I include custom code in the generated initialization function when an initialize block is present in the model? If I try to add custom code to the Initialize function field in the "Code Generation > Custom Code" pane of the configuration parameters I receive the following error when generating code for the model:
Addition of custom initialization and custom termination code using the 'Configuration Parameters > Code Generation > Custom Code'
dialog is not supported in models containing the Initialize, Reset or Terminate Function blocks.
I would like this custom code to only appear in the generated code and not execute when simulating.

 Accepted Answer

As a workaround, you can create a wrapper function that includes all of the custom code you would like to execute upon model initialization. In order to include this wrapper function in the generated code, place a MATLAB Function block within the Initialize Function block. Use the "coder.target" and "coder.ceval" commands in the MATLAB Function block to conditionally call the wrapper function when generating code for the model.
For example, the contents of the MATLAB function block would look like the following:
function y = fcn(u)
y=u;
if coder.target('Sfun')
% do nothing during Simulation
else
% call external C code in the generated <model>_initializate function
coder.cinclude('foo.h'); % include custom header files
coder.ceval('foo', 10, 20); % execute custom C code in generated code
end
end
In the generated "<model>.c" file, under the "<model>_initialize" function you would see the following:
void <model>_initialize(void)
{
...
foo(10.0, 20.0);
...
}
In the generated "<model>.h" file you would see the following include directive:
#include foo.h

More Answers (0)

Categories

Find more on Simulink Coder in Help Center and File Exchange

Products

Release

R2019a

Community Treasure Hunt

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

Start Hunting!