Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Python function from MATLAB

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

like image 879
Sarah Avatar asked Nov 10 '09 12:11

Sarah


People also ask

Can you call Python scripts from MATLAB?

You can call functionality from Python® libraries or execute Python statements directly from MATLAB®.


1 Answers

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 >> 
like image 159
Adrian Avatar answered Sep 30 '22 21:09

Adrian