How to convert fmincon to C code?
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
1 comentario
Qiaohui He
el 19 de Abr. de 2023
Hi, I also face this problem, could you please share your solution?
Respuestas (1)
Ivo Houtzager
el 27 de Sept. de 2020
Editada: Ivo Houtzager
el 27 de Sept. de 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 https://www.mathworks.com/help/optim/ug/code-generation-in-fmincon.html. The following example is based on the examples provided in https://www.mathworks.com/help/optim/ug/code-generation-for-optimization.html.
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 https://www.mathworks.com/matlabcentral/fileexchange/58942-simulink-coder-support-package-for-stmicroelectronics-nucleo-boards.
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)];
end
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.
0 comentarios
Ver también
Categorías
Más información sobre STMicroelectronics Discovery Boards en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!