Find minimum of function using genetic algorithm in Simulink

15 次查看(过去 30 天)
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

采纳的回答

Ayush Aniket
Ayush Aniket 2023-8-14
编辑:Ayush Aniket 2023-8-16
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!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Genetic Algorithm 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by