1

I'm trying to use MATLAB with Python and would like to use MATLAB's fmincon to optimize a Python function. Here's an example of what I'm trying to achieve (in Python).

import matlab.engine
from scipy import stats

m = matlab.engine.start_matlab()

def my_fun(x):
    return -stats.norm.pdf(x, 0, 1)

x0 = matlab.double([-1, 2])
A = matlab.double([1, 2])
b = 1
x = m.fmincon(my_fun, x0, A, b, nargout=2)
print(x)
m.exit()

However, I get the following error:

TypeError: unsupported Python data type: function

I then tried calling Python from MATLAB from Python (!) in this way:

x = m.fmincon(m.py.my_fun, x0, A, b, nargout=2)

But I got this error:

TypeError: unsupported Python data type: matlab.engine.matlabengine.MatlabFunc

Is there any different workaround? I think the second thing I tried should work in principle, but the way I implemented it is wrong.

gimi
  • 395
  • 3
  • 13
  • Looks like it *has* to be a native MatLab function: https://www.mathworks.com/help/optim/ug/fmincon.html#busog7r-fun. Not sure how you generated m.py.fun, but a Python function from the Matlab runtime would not be a Matlab function? – lmeninato Mar 23 '22 at 18:47
  • @lmeninato sorry, I meant to say m.py.my_fun - just edited the question – gimi Mar 24 '22 at 00:52
  • @lmeninato you're right though, it looks like it may not be possible: https://www.mathworks.com/matlabcentral/answers/427679-how-to-pass-functions-to-a-matlab-function-in-the-python-api – gimi Mar 24 '22 at 15:01

0 Answers0