Running a genetic algorithm with a c code build by Simulink Coder!

4 vues (au cours des 30 derniers jours)
Emmanuel Walter Djeutsop Sonkoua
Hello to everyone,
I am working on a project and the goal is to tune a PI Controller for my model using the genetic algorithm. For faster execution, the genetic algorithm should run with a c code (replacing the simulink model). For C code generation, simulink coder is used.
I can't call the c code inside the callback function, wich is called from the genetic algorithm. The c code for the model simulation should be a function taken two parameters (the parameters to optimize).
The following code is the callback function wich is called by the genetic algorithm:
The main problem is following: how can i generate a function from my simulink model wich will take two parameter as variables?
function y = GNMReglerPIfcn(x)
%% parameter definition
K = 1;
w0 = 131;
T1 = 1/w0;
R=3;
L=0.01;
K_M=1;
J=0.01;
KR = x(:,1);
KI = x(:,2);
%%%%%% call c function
ysim= simulation(KR,KI) %%% call c function simulation.c
% calcule the deviation
e = yr-ysim; % yr is the real response
% fitness function
y = sum(abs(e).^2);
end

Réponses (1)

Ashutosh Thakur
Ashutosh Thakur le 22 Jan 2024
Modifié(e) : Ashutosh Thakur le 22 Jan 2024
Hi Emmanuel,
In order to create a MATLAB function which will take two arguments as input and call a C function following steps can be followed:
  • Create a Model whose C code has to be generated, you can also create a Simulink Function if it is required.
  • Now generate the code using Simulink Coder product, the header and source files for that model would be generated.
  • You can call this external C code from MATLAB using "coder.ceval" and "coder.cinclude" functions which are present in MATLAB. This can be implemented in the following way:
coder.cinclude('myfiles.h');
ysim = coder.ceval('simulation',KR,KI);
Here "myfiles.h" is the header file where C code is present, and "simulation" is the name of the function which is written in C code. Also make sure that header and source files are present in same directory where the MATLAB Script is present.
Kindly take reference from the following documentation links regarding the usage of external C code in MATLAB:
I hope that above suggestions helps you in integrating C code with your MATLAB script.

Community Treasure Hunt

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

Start Hunting!

Translated by