Call Python function from MATLAB
I need to call a Python function from MATLAB. how can I do this?
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
>>
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']
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);