optimization: calling fmincon in Simulink (embedded block)
96 views (last 30 days)
I am going to implement a model predictive controller in Simulink. Therefore I need to solve a constrained optimization problem, thus finding the vector that mimimises a certain multi-variable function, subject to constraints. (I do know there is a MPC block in Simulink, but I need to implement it myself as part of a bigger Simulink model).
In Matlab this is possible using fmincon. So I tried using an embedded Matlab block in Simulink where fmincon was called, but this does not work. I also tried "coder.extrinsic('fmincon')" code but that did not work.
Can anybody tell me if it is possible to use fmincon in a SIMULINK model (thus not working in a .m Matlab file) or if there are alternatives? Or do I have to try to implement the algebra behind this function (quadratic programming etc.) in Simulink myself?
All help appreciated! Maarten
Matteo Ragni on 29 May 2018
I will post the same answer I gave on Stack Overflow on the same topic
You need to call the optimal problem function with coder.extrinsic.
Instead of using coder.extrinsic on the fmincon function, I usually write a wrapper for the optimization problem that I have to solve as a .m file function for Matlab (namely opt_problem) and declare coder.extrinsic('opt_problem') in the simulink Matlab function. I'll give you a simple example:
Consider this Simulink "model", in which at each integration step I want to solve a linear regression problem on some generated data. The optimization problem is something in the form:
minimize (y - m x - q)²
subject to 0 ≤ m ≤ 1
0 ≤ q ≤ 1
The scheme is really simple, bet the regressor calls fmincon:
Let's see inside the regressor:
function [m, q] = regressor(xs, ys, mic, qic)
coder.extrinsic('opt_problem'); % <- Informing the Coder
m = 0;
q = 0;
[m, q] = opt_problem(xs, ys, mic, qic); % <- Optimal problem wrapper call
this function is only a wrapper for an external function `opt_problem`. Let'see it (it has two functions inside):
function [m, q] = opt_problem(xs, ys, mic, qic)
fmincon_target = @(mq)(target(mq, xs, ys));
mq = fmincon(fmincon_target, [mic; qic], , , , , [0; 0], [1; 1]);
m = mq(1);
q = mq(2);
function r = target(mq, xs, ys)
r = norm(ys - xs.*mq(1) - mq(2));
and that's all. As you can see in the picture, the scheme runs and the solution are the m, q parameters (in the two displays) that minimize the target function while respecting the constraints (m = 1.2 → m_opt = 1).