user1612986
user1612986

Reputation: 1415

matlab fmincon calling from c++

I am trying to call Matlab's fmincon function from c++. I am using the call

mxcallMatlab(2, &arg1, 4, &arg2, "fmincon");

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]?

Upvotes: 1

Views: 663

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

As found here:

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.

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, ...)

Upvotes: 1

Related Questions