running python script in matlab
73 views (last 30 days)
Hi, I have one python script and i want to execute that in matlab.I want to run that python function in matlab and saving the putput in workspace. Please can anybody help me in fixing this error. Thanks in advance!
Geoff Hayes on 7 Sep 2014
Xu - how complicated is your python script? Are there many inputs and several output? An interesting solution from call python function from matlab (1) exists and it involves creating a python m-file (from the MATLAB perl.m, replacing the perl text with python. I tried it, along with their example, and it worked well. Basically it involves just creating a command string and evaluating it with the MATLAB dos or unix commands (depending upon your OS).
Or, instead of creating the python.m file, you can just try with the same with a call to system. See call python function matlab (2) If your python script squares a number (like in the linked example) then you could simply write
commandStr = 'python /Users/myName/pathToScript/sqr.py 2';
[status, commandOut] = system(commandStr);
fprintf('squared result is %d\n',str2num(commandOut));
In the above, the path to the python script is explicitly defined. If the system call is successful, then status is zero, and we print out the result. Note that since the commandOut is a string, we have to convert it to a number.
For a simple example, this works very well. For a more complicated python script, it might be a little tricker.
More Answers (3)
Sarah Palfreyman on 3 Oct 2014
As of MATLAB R2014b there exists bi-directional support for directly interfacing MATLAB and Python.
Arwel on 26 Jan 2017
I haven't tried this, but one approach I have seen is to embed a Python interpreter in C, and then to call this as a mex file. There are a few examples around (e.g. here http://stackoverflow.com/questions/1700628/embed-python-in-matlab-mex-file-on-os-x).... There are other examples around if you google for them also.