Does MPC with fmincon from a Matlab script work with a Simulink model?
Show older comments
I want to run MPC in Matlab, where I optimize the input U, which is fed into a Simulink model and then calculates the state trajectory of my system. The Simulink model is a trivial, discrete LTI-system. The goal is to have an arbitrary system later.
Here is a screenshot of the given system:

So for this system, I want to minimize the input "input_model" by using fmincon from a matlab script.
The definition of the optimization problem is as follows:
op = optimoptions('fmincon','Algorithm','sqp');
cost_fun = @(u)MPC_cost(u,x_current,Q,R,N,t_start_MPC,t_sample);
opt = fmincon(cost_fun,u0,[],[],[],[],u_min,u_max,[],op);
where u is the input to optimize, x_current is the current system state gained from the Simulink model, Q,R are the weighting matrices for the cost function, N is the prediction horizon, t_start_MPC the starting time (needed for the FromWorkspace block "input_model") and t_sample the fundamental sampling time.
function cost = MPC_cost(U,x_current,Q,R,N,t_start_MPC,t_sample)
%% init state prediction
x_pred = zeros(2,N+1);
u_MPC = zeros(N,2);
x_pred(:,1) = x_current;
%% optimization variable U
u_MPC(:,1) = t_start_MPC:t_sample:(t_start_MPC + (N-1)*t_sample);
u_MPC(:,2) = U;
input_model = u_MPC;
%% simulation to optimize input
x_init = x_pred(:,1);
optimization.StartTime = num2str(t_start_MPC);
optimization.StopTime = num2str((t_start_MPC + (N-1)*t_sample));
x_MPC = sim("Simu.slx",optimization);
%% state prediction vector from simulation
x_pred = x_MPC.xout.getElement(1).Values.data';
%% init cost
sum = 0;
%% cost function under prediction
for J = 1:N
sum = sum + x_pred(:,J)'*Q*(x_pred(:,J)) + U(J)'*R*U(J);
end
cost = sum;
end
The cost function to optimize is of the form
.
As can be seen I first initalize with zeros, then define the input to optimize, where the second column of "input_model" consists of the values of the variable U.
I then simulate for the given time (start time + prediction horizon*sample time = N prediction steps). And store the result of the state trajectory in x_pred and use this variable as well as U to calculate the value of the cost function.
This optimization routine is then called from a script, where I simulate for a given amount of time.
[u_opt] = (solveMPC(Q,R,N,u_min,u_max,x_current,u0,t_start,t_sample))';
However, the result is always an input almost equal zero, which does not happen if I instead simulate the given linear system directly in Matlab with the help of the "lsim" function. Does anyone know if the way I try to do this even works? I would be very thankful for any ansight!
1 Comment
Balaji
on 6 Sep 2023
Can you share your code with the simulink model ?
Answers (0)
Categories
Find more on Refinement in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!