Find minimum of function using genetic algorithm in Simulink
16 ビュー (過去 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
0 件のコメント
採用された回答
Ayush Aniket
2023 年 8 月 14 日
編集済み: Ayush Aniket
2023 年 8 月 16 日
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 Center および File Exchange で Genetic Algorithm についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!