MATLAB Answers

How to convert fmincon to C code?

13 views (last 30 days)
Muhammad Bilal Aziz
Muhammad Bilal Aziz on 15 Jul 2020
Edited: Ivo Houtzager on 27 Sep 2020
Hello, I am using stm32 nucleo board microcontroller and I want to implement the built in fmincon optimization algorithm of matlab on to that microcontroller. For that I have to convert this code into C. I have tried by Matlab embedded C coder but most of the functions are not supported by it. I am also trying to implement it by making its model in simulink by the code requires a function handle which is giving me the error in simulink. I am using Matlab 2020a version. Can anyone guide me how to implement this code on stm32 nucleo boards. Thanks in advance

Answers (1)

Ivo Houtzager
Ivo Houtzager on 27 Sep 2020
Edited: Ivo Houtzager on 27 Sep 2020
The fmincon is supported by code generation, but there are limitations on syntax and options which can be used, see the following link for more details The following example is based on the examples provided in
First you will have to install the "Simulink Coder Support Package for STMicroelectronics Nucleo Boards". This can be done using the "Get Add-Ons" button on the ribbon, or by donwloading installer from the link
Insert a "MATLAB Function" block in the Simulink Model. Open the "MATLAB Function" block and copy paste the following code as example.
function x = test_rosen()
opts = optimoptions('fmincon','Algorithm','sqp','MaxIterations',20);
[x fval] = fmincon(@rosenbrockwithgrad,[-1,1],[],[],[],[],[-3,-3],[3,3],[],opts);
function [f,g] = rosenbrockwithgrad(x)
% Calculate objective f
f = 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
if nargout > 1 % gradient required
g = [-400*(x(2) - x(1)^2)*x(1) - 2*(1 - x(1));
200*(x(2) - x(1)^2)];
In the main Simulink model window, select the modelling tab and open "Model Settings". In configuration window, set the "System target file" to "ert.tlc" in Code Generation options. After setting the embedded coder target, set the "Hardware board" in Hardware Implementation options to the correct Nucleo board used.
In the main Simulink model window, select the c code tab and select "Generate Code" or "Build" (does also make of generated code) in the ribbon. This will create folder name_ert_rtw containing the generated code and make files.

Community Treasure Hunt

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

Start Hunting!

Translated by