Find minimum of function using genetic algorithm in Simulink

조회 수: 16 (최근 30일)
xin lin
xin lin 2023년 5월 28일
편집: xin lin 2023년 8월 17일
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!
  댓글 수: 1
xin lin
xin lin 2023년 8월 17일
편집: xin lin 2023년 8월 17일
Hi Ayush,
Thanks for answer. This is very helpful.
Best regards,
Xin

댓글을 달려면 로그인하십시오.

추가 답변 (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