tags:

views:

1441

answers:

3

Hello, I need to call a python function from MATLAB. Any ideas how can I do this?

+4  A: 

EDIT: 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.

Jacob
+3  A: 

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
>>
Adrian
`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." - http://www.mathworks.com/access/helpdesk/help/techdoc/ref/perl.html
Jacob
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.
Adrian
+1 - The MATLAB example code looks great - could you post (code/link) `python.m`? What are the limitations of the data returned - only scalar?
Jacob
A: 

Since python is a better glue language, it may be easier to call the matlab part of your program from python instead of vice-versa.

Check out: http://mlabwrap.sourceforge.net/

Drew Wagner