matlab fmincon调用从c ++ [英] matlab fmincon calling from c++
问题描述
我试图从c ++调用Matlab的 fmincon
函数。我正在使用调用
I am trying to call Matlab's fmincon
function from c++. I am using the call
mxcallMatlab(2, &arg1, 4, &arg2, "fmincon");
其中 arg2
是一个Matlab mxArray
数组4(即它被定义为 mxArray * arg2 [4]
)。 arg2
接受 fmincon
的四个不同参数。 arg2 [0]
问题是我如何将目标函数句柄传递给 arg2 [0] <0>
fmincon
/ code>。
我的目标函数没有在Matlab中定义,而是在c ++中。我将目标函数指针转换为double(这是我必须做的,因为对Matlab的所有输入都是double),然后传递给 arg2 [0]
?
where arg2"
is a Matlab mxArray
array of dimension 4 (i.e. it is defined as mxArray *arg2[4]
). arg2
takes in the 4 different argument to fmincon
. arg2[0]
should be the objective function handle which fmincon
uses as its first argument.
The question is how do I pass the objective function handle to arg2[0]
.
My objective function is not defined in Matlab, but in c++. Shall I cast my objective function pointer to double (this I have to do because all inputs to Matlab are double), and then pass that to arg2[0]
?
推荐答案
href =http://www.mathworks.de/matlabcentral/answers/44778 =nofollow>此处:
As found here:
只有MATLAB可以调用MATLAB函数句柄。
中的函数句柄MATLAB是一个数据结构,包括一个
引用一个数据块,该数据块将MATLAB代码存储在一个预解析的
线程解释器格式,需要由MATLAB
引擎解释。 MATLAB .m代码不能编译成机器语言,只能
到链接的数据结构。
Only MATLAB can invoke MATLAB function handles. Function handles in MATLAB are a data structure that include (amongst other things) a reference to a data block that stores MATLAB code in a pre-parsed threaded-interpreter format that needs to be interpreted by the MATLAB Engine. MATLAB .m code does not compile down to machine language, only to linked data structures.
你想要的,直接为你想要的。你必须在一个单独的MEX文件中定义目标函数,在Matlab中定义一个函数句柄,并将它传递给MEX,调用 fmincon
。所以,像
So you cannot achieve what you want, as directly as you want it. You'll have to define the objective function in a separate MEX file, define a function handle to it in Matlab to it, and pass that on to the MEX where you call fmincon
. So, something like
[sol, fval, ...] = your_main_mex(@your_objective_mex, ...)
这篇关于matlab fmincon调用从c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!