Hello, I need to call a python function from MATLAB. Any ideas how can I do this?
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.
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
>>
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/