I am trying to implement a particular type of model predictive control in the Simulink-Matlab framework. To do so, my plan was to have the dynamic model in Simulink call an external Matlab S-function which in turns runs an optimization that calls a different Simulink file. Hence, the program flow would be as follows:
Simulink -> Matlab (fmincon
or quadprog
) -> Simulink.
As you can see, the Matlab S-function would call either fmincon
or quadprog
, but I would like to use fmincon for my particular control type. Please, ignore any issues related to computational efficiency so far.
I tried this approach, but there are two very clear problems: * Firstly, in order to compile the code without errors (basically obtaining a .mex file, I do not need to program in C yet), I added the command
coder.extrinsic('fmincon');
This was required because otherwise Simulink is unable to compile the mex file. However, if you do this, then you get the following error:
Function handles cannot be passed to extrinsic functions.
I tried to change my cost function calling Simulink to another, simpler cost function (x.^2
), but I still get the error.
Looking for a solution to the problem, I found the same question (i.e. how to call fmincon
from a Matlab function within Simulink) on the Mathworks blog, but with no answer (https://uk.mathworks.com/matlabcentral/answers/65202-optimization-calling-fmincon-in-simulink-embedded-block).
Could anyone give me a hand? Thanks in advance!
MATLAB Function
block, not an m-code S-Function.MATLAB Function
blocks get converted to C and compiled during model initialization and only support a subset of the MATLAB language. You need to write an m-code S-Function. They do not convert the m-code to C but rather run it (as interpreted code) in the standard MATLAB computational engine, and hence support the full MATLAB language. - Phil GoddardMATLAB Function
block as a wrapper around another m-code function. In theMATLAB Function
you define your other function as extrinsic and just pass appropriate inputs to it, and get output from it back into the Simulink model. Then in the other function define the optimization that needs to be performed. - Phil Goddardfmincon
comes from. - Filip Cvejic