Call Python Function from Matlab

Call Python from Matlab

You need to open Matlab from the terminal:

Go to the bin:

cd /Applications/MATLAB_R2019a.app/bin/

Open it:

./matlab

Next, to use Python type:

!python

This answer assumes that you have already installed Python on your system.

Sample Image

Call a python function that takes in a MATLAB function handle as argument from matlab

I suspect that what you want can't directly 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.

This very strongly suggests that once you have a MATLAB anonymous function you can't pass it to python.

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.

We could try converting your MATLAB anonymous function to a python one, but I have to note upfront that it's messy and I'd avoid doing this if I were you. Since lambdas aren't directly exposed by MATLAB's Python API:

>> py.lambda
Unable to resolve the name py.lambda.

we have to resort to calling Python's eval using a python lambda (because exec also doesn't seem to be exposed):

>> py_f = py.eval('lambda x: x**2', py.dict());
>> py_f(3)

ans =

9

(Kudos to @yuyichao for fixing this snippet of mine by pointing out the missing globals dict that needs to be passed.)


However, a 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 probably be the straightforward way.



Related Topics



Leave a reply



Submit