1
votes

I'm trying to use the scipy.optimize.differential_evolution (python) from MATLAB environment.

So far, I am able to call the differential_evolution function. The only problem is that it apprently cannot receive MATLAB function handles as an argument.

I get the following error:

Error using py.scipy.optimize.differential_evolution Handle to MATLAB function '@(x)x(1).^2.*x(2).^2' is not supported. Use a handle to a Python function.

Is there some neat way or function to "convert" a MATLAB function handle into a python function, so that I could use the neat optimization function from scipy?

1

1 Answers

1
votes

I'm not sure but I suspect that what you want can't be done.

Firstly, anything in the python interface will give you that error if you pass it a MATLAB anonymous function:

>> py.print(@(x) x)     
Error using py.print
Handle to MATLAB function '@(x)x' is not supported. Use a handle to a Python function.

So it seems the engine means it, and you have to give up MATLAB functions. We could try converting your anonymous function to a python one...but I couldn't figure out how this was possible. I suspect it isn't possible at all, since the most straightforward and simplest custom function would be a lambda. But py.lambda doesn't exist and we can't even fool the MATLAB engine by calling py.eval:

>> py.lambda           
Undefined variable "py" or class "py.lambda".

>> py.eval('lambda x: x')
Python Error: SystemError: frame does not exist

>> py.eval('def foo(x): return x')
Python Error: SystemError: frame does not exist

This very strongly suggests that once you have a MATLAB anonymous function you can't turn it into a python one.

The straightforward question is: do you really need a MATLAB anonymous function? You could just as well use a proper python function (or lambda) and pass possible other arguments to the underlying scipy.optimize function as args. You could define your custom function in a python file and import that from MATLAB and use the corresponding function handle. This would be the straightforward way out from your situation.


Also note that while the lack of MATLAB function handle support is not explicitly mentioned among the limitations, the section of the documentation detailing supported data types makes this remark:

MATLAB Input Argument Type — Scalar Values Only
function handle @py.module.function, to Python functions only

The distinction for Python functions is in line with the fact that even the simplest Python functions refuse to accept MATLAB function handles.