Find minimum of function using genetic algorithm in Simulink

16 visualizaciones (últimos 30 días)
xin lin
xin lin el 28 de Mayo de 2023
Editada: xin lin el 17 de Ag. de 2023
Hi
Thank you for reading this question!
I try to apply the solver "ga" in Simulink. Then, the simulation shows errors, which is "Function 'ga' not supported for code generation". After, I added the command "coder.extrinsic('ga')" in front of the code. However, the error is "Function handles cannot be passed to extrinsic functions." The code and simulation are shown below. I'm not sure if the solver "ga" can be applied to Simulink. Could anyone help me or share the relevant link?
Many thanks in advance!
function [y, fval, exitflag] = fcn(lb, ub)
coder.extrinsic('ga')
fun = @(x)100*(x(2)-x(1)^2)^2 + (1-x(1))^2;
A = [];
b = [];
Aeq = [];
beq = [];
[y, fval, exitflag] = ga(fun,2,A,b,Aeq,beq,lb,ub)
end

Respuesta aceptada

Ayush Aniket
Ayush Aniket el 14 de Ag. de 2023
Editada: Ayush Aniket el 16 de Ag. de 2023
Hi xin lin,
As the error suggests, you need to refactor your code so that you don't pass function handles across the extrinsic function call boundary. You can wrap up all of that code in yet another function, let's call it myCode.m. Then, declare that whole function as extrinsic and call it from your MATLAB Function block as shown below:
function [y, fval, exitflag] = fcn(lb, ub)
coder.extrinsic('mycode');
y = zeros(1,2);%preintialize this with expected dimensions
fval = zeros(1);%preintialize this with expected dimensions
exitflag = zeros(1);%preintialize this with expected dimensions
[y, fval, exitflag] = myCode(lb,ub);
end
function [y, fval, exitflag] = myCode(lb,ub) %define this in MATLAB workspace
fun = @(x)100*(x(2)-x(1)^2)^2 + (1-x(1))^2;
A = [];
b = [];
Aeq = [];
beq = [];
[y, fval, exitflag] = ga(fun,2,A,b,Aeq,beq,lb,ub);
end
Hope this helps!
  1 comentario
xin lin
xin lin el 17 de Ag. de 2023
Editada: xin lin el 17 de Ag. de 2023
Hi Ayush,
Thanks for answer. This is very helpful.
Best regards,
Xin

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Genetic Algorithm en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by