Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
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()){

Antworten (1)

Divyanshu am 26 Feb. 2024
Bearbeitet: Divyanshu am 26 Feb. 2024
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!


Mehr zu Call MATLAB from .NET finden Sie in Help Center und File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by