Function 'fmincon' not supported for code generation

Illustration
Albrecht - 2021-09-30T14:04:34+00:00
Question: Function 'fmincon' not supported for code generation

Hello,   im currently trying to implement nonlinear MPC in MATLAB/Simulink using the MATLAB function block. function u_mpc = MPC(x, u_mpc, u_0, A_ineq, b_ineq, Q_mpc, R_mpc) costfunc = @(x,u) (x)'*Q_mpc*(x) + (u_mpc)'*R_mpc*(u_mpc); u_mpc = fmincon(costfunc, u_0, A_ineq, b_ineq); end The state x is provided by a plant model, the costfunction is a simple quadratic cost with weight matrices, the matrices are taken from the workspace.   Running the Simulink model results in the error: Function 'fmincon' not supported for code generation.   I'm using the 2018b version normally, tried using 2021a but got the same error.   Is there a mistake in the code or is it simply not possible to use fmincon inside a MATLAB function block?

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

fmincon codegen support was added in R2019b. Also, optimOptions is the last argument for fmincon, you should pass other arguments as empty ([]) if you are not using them. For example,
 
 
function u_mpc = MPC(x, u_mpc, u_0, A_ineq, b_ineq, Q_mpc, R_mpc)
    costfunc = @(x,u) (x)'*Q_mpc*(x) + (u_mpc)'*R_mpc*(u_mpc);
    options = optimoptions('fmincon','Algorithm','sqp');
    Aeq = [];
    beq = [];
    lb = [];
    ub = [];
    nonlcon = [];
    u_mpc = fmincon(costfunc,u_0,A_ineq,b_ineq,Aeq,beq,lb,ub,nonlcon,options);
end


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!