Call Python function from MATLAB

129,473

Solution 1

I had a similar requirement on my system and this was my solution:

In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like

C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m

Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.

Example

A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.

import sys

def squared(x):
    y = x * x
    return y

if __name__ == '__main__':
    x = float(sys.argv[1])
    sys.stdout.write(str(squared(x)))

Then in MATLAB

>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>

Solution 2

With Matlab 2014b python libraries can be called directly from matlab. A prefix py. is added to all packet names:

>> wrapped = py.textwrap.wrap("example")

wrapped = 

  Python list with no properties.

    ['example']

Solution 3

Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/

You can do something like this easily:

[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);

Solution 4

You could embed your Python script in a C program and then MEX the C program with MATLAB but that might be a lot of work compared dumping the results to a file.

You can call MATLAB functions in Python using PyMat. Apart from that, SciPy has several MATLAB duplicate functions.

But if you need to run Python scripts from MATLAB, you can try running system commands to run the script and store the results in a file and read it later in MATLAB.

Solution 5

As @dgorissen said, Jython is the easiest solution.

Just install Jython from the homepage.

Then:

javaaddpath('/path-to-your-jython-installation/jython.jar')

import org.python.util.PythonInterpreter;

python = PythonInterpreter; %# takes a long time to load!
python.exec('import some_module');
python.exec('result = some_module.run_something()');
result = python.get('result');

See the documentation for some examples.

Beware: I never actually worked with Jython and it seems that the standard library one may know from CPython is not fully implemented in Jython!

Small examples I tested worked just fine, but you may find that you have to prepend your Python code directory to sys.path.

Share:
129,473
Sarah
Author by

Sarah

Updated on November 18, 2020

Comments

  • Sarah
    Sarah over 3 years

    I need to call a Python function from MATLAB. how can I do this?

  • Harsh Pathak
    Harsh Pathak over 14 years
    perl just makes a system call to execute the Perl script - there is no transfer of data between the Perl script and MATLAB apart from "the results of attempted Perl call to result and its exit status to status." - mathworks.com/access/helpdesk/help/techdoc/ref/perl.html
  • Felix Ribeiro
    Felix Ribeiro over 14 years
    I agree it just makes a system call but why make things complicated with mex functions and sockets if it isn't required? At a simple level the call to python does have a simple data transfer. I'll update the answer with an example.
  • Harsh Pathak
    Harsh Pathak over 14 years
    +1 - The MATLAB example code looks great - could you post (code/link) python.m? What are the limitations of the data returned - only scalar?
  • Amro
    Amro almost 12 years
    +1 thank you for an excellent solution. Please consider hosting the project on GitHub, so that others might find it as well
  • Amro
    Amro almost 12 years
    For those interested, I just found two other similar projects: pythoncall and pymex (haven't tried them myself yet)
  • Amro
    Amro almost 12 years
    it is definitely easier to integrate. Too bad that as of yet, you can't use modules like Numpy/Scipy/matplotlib with Jython (on the account of C extensions). Those libraries are really Python's strong point when it comes to scientific computing
  • kay
    kay almost 12 years
    It's difficult to answer the question. One could just open Python (out of Matlab) and write to/read from the REPL shell, too. I guess a seamless integration will only be possible with Jython. Then again using ctypes it might be easy to integrate Octave, but not Matlab, into CPython.
  • kay
    kay almost 12 years
    (Granted, Octave is a puny replacement for Matlab.)
  • Amro
    Amro almost 12 years
    CPython allows to embed its interpreter into C programs (which is what @algoholic has done using MEX-files). The bulk of the code deals with converting back and forth between Python types (numpy.ndarray was used as the equivalent of MATLAB N-D matrices), and MATLAB's types (really mxArray in MEX).
  • Amro
    Amro almost 12 years
    The whole thing is similar to what you've shown above, only using Python's C API instead of Jython Java API to evaluate arbitrary expressions in the interpreter... Plus you can import any installed Python module, including the whole PyLab ensemble
  • whlteXbread
    whlteXbread over 11 years
    This is what I had been doing, but I'm running into a mysterious problem—one of the arguments to my python script is a file. When called from MATLAB, the python script can't find the file (despite all scripts being in the same directory as the file, and despite specifying the full path in the MATLAB script). Maddening.
  • Amro
    Amro over 11 years
    didn't work for me on Windows.. (I created the env. var. the usual way)
  • quazgar
    quazgar over 11 years
    Hmm, I suppose you checked from within Matlab that the variable was really set? But I would not be too surprised if Matlab had different criteria in Windows to decide which shell to use.
  • Amro
    Amro over 11 years
    yes I checked getenv('SHELL') within MATLAB.. Anyway you should probably mention it that this trick is unfortunately Linux/Mac only
  • Amro
    Amro over 11 years
    +1 there seems to be a mention of SHELL variable here: mathworks.com/help/matlab/ref/matlabunix.html (the windows counterpart page, doesnt have it)
  • Donbeo
    Donbeo about 10 years
    Can we pass also array as argument to the python file?
  • jrh
    jrh over 7 years
    Note that this works but it's a hack, there's a lot of paths that don't really go anywhere, e.g., fullfile(matlabroot, 'sys\python\win32\bin\'); points to a path that isn't really there, there aren't any python error messages defined, so the message('MATLAB:python:<>') error messages won't work in the CTRL+F'd Perl.m
  • Bastian Ebeling
    Bastian Ebeling almost 7 years
    This is indeed a cool Feature - but seems to be incomplete - for example I can not use sklearn that way For Details see my question.
  • Giorgio Balestrieri
    Giorgio Balestrieri over 5 years
    This answer is not up to date anymore. As pointed out below, since Matlab 2014b you can directly use (some) Python functionalities by just pre-prending py. to python calls.
  • Kouichi C. Nakamura
    Kouichi C. Nakamura about 5 years
    The py prefix can be used for user defined python modules (scripts) as well: eg. names = py.mymod.search(N). The right documentation page is this: uk.mathworks.com/help/matlab/matlab_external/…
  • NeStack
    NeStack about 5 years
    The suggestions looks great, but I get the error message "'python' is not recognized as an internal or external command, operable program or batch file. "
  • NeStack
    NeStack about 5 years
    This is the simplest solution I have found here, it should be much further up!