Find minimum of function using genetic algorithm in Simulink
15 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Ayush Aniket
on 14 Aug 2023
Edited: Ayush Aniket
on 16 Aug 2023
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!
More Answers (0)
See Also
Categories
Find more on Genetic Algorithm in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!