필터 지우기
필터 지우기

Matlab invocation from C# - how to pass in a function as a function argument to fminunc

조회 수: 3 (최근 30일)
I am trying to use the Matlab optimization toolbox from C# and want to do all my coding within c# , using the Matlab Engine API.
I am trying this with the code from the example given in "Tutorial for Optimization Toolbox"
f = @(x,y) x.*exp(-x.^2-y.^2)+(x.^2+y.^2)/20;
fun = @(x) f(x(1),x(2));
options = optimoptions('fminunc','Algorithm','quasi-newton');
[x, fval, exitflag, output] = fminunc(fun,x0,options);
When I want to invoke the function fminunc - the first argument I need to pass in is a fuction name. I am facing two problems with this
1) How do I write the first line in C# code ? This anonymous function "f = @(x,y) x.*exp(-x.^2-y.^2)+(x.^2+y.^2)/20;"
2) How do I pass in "fun" as the first argument when invoking fminunc
using (dynamic matlab = MATLABEngine.StartMATLAB()){
...
...
matlab.fminunc(???
...
}

답변 (1개)

Divyanshu
Divyanshu 2024년 2월 26일
편집: Divyanshu 2024년 2월 26일
Hi Tanveer,
In order to use the MATLAB Optimization toolbox from C#, you are using MATLAB.Engine API to convert/use your C# code to execute the example given in 'Tutorial for Optimization Toolbox'.
In this workflow you are facing certain challenges, please refer the following pointers for possible workarounds:
  • If direct conversion of code given in example to C# is difficult, you can write the entire piece of code in a new normal MATLAB function.
  • Now you can simply call the newly created function from the C# code using MATLAB Engine API.
The above workaround no more requires conversion of anonymous function to C# and also now no need to pass 'fun' as argument, because the entire code is just inside another MATLAB function which is directly called from C# using Engine API.
You can refer the following documentation for more information on how to 'Execute MATLAB functions from .NET':
Hope it helps!

카테고리

Help CenterFile Exchange에서 Call MATLAB from .NET에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by