MATLAB outputs all the parameters to a file and then uses the system command to tune the Python script. Python script read the file to do the calculation and write the file. Finally matlab read the file to get the result. Suppose the use of a Python script is:
Python xxx.py in.txt OUT.txt
Then MATLAB calls the command:
[Status, Cmdout] = System (' python xxx.py in.txt out.txt ')
The system function of MATLAB is used to send an instruction to the operating system and get the output of the console, which can print out the console output directly in command window or save it in a variable. Similar to system, there are DOS functions and UNIX functions, which I think are a wrapper over the system function, and the system function of MATLAB may be the wrapper of the library function system for C.
First write a MATLAB program called Python script, namely PYTHON.M
function [result status] = Python (varargin)
% call Python
% command string
cmdstring= ' python ';
For i = 1:nargin
thisarg = varargin{i};
If IsEmpty (Thisarg) | ~ischar (Thisarg)
error ([' All input arguments must is valid strings. ']);
ElseIf exist (thisarg) ==2
% This is a file available in the MATLAB path
if IsEmpty (dir (thisarg)) gets the
full path
thisarg = which ( THISARG);
End
ElseIf i==1
% The first parameter is the Python file-must be an available file
error ([' Unable to find Python file: ', Thisarg]);
End
% If there are spaces in the thisarg, enclose it in double quotes if any
(Thisarg = = ")
thisarg = ['", Thisarg, ' "];
End
% adds thisarg behind cmdstring
cmdstring = [Cmdstring, ', Thisarg] end
% Send command
[Status,result] =system (cmdstring);
End
You can use this function to invoke the Python script. Here's an example of invoking the Python script matlab_readlines.py (saved in the current directory of MATLAB)
Import SYS
def readlines (fname):
try:
f=open (fname, ' R ')
Li=f.read (). Splitlines () cell=
' {' + Repr (LI) [1:-1]+ '} '
f.close ()
print cell
except ioerror:
print ' Can ' t open file ' +fname
if ' __main __ ' ==__name__:
If Len (sys.argv) <2:
print ' No file specified. '
Sys.exit ()
Else:
readlines (sys.argv[1])
This script is used to read a text file, and to generate a MATLAB-style cell array definition string, each cell is a line of text. Put a Test text file Test.txt in the current directory of MATLAB, the contents are as follows:
This is Test.txt
It can help you test python.m
and matlab_readlines.py
Test:
In the MATLAB command window, enter:
>> Str=python (' matlab_readlines.py ', ' test.txt ');
>> eval ([' c= ' str])
c =
' This is Test.txt ' [1x29 char] [1x23 Char]
>> Celldisp (c)
C{1} = This is Test.txt
C{2} = It can help you test python.m
C{3} = and matlab_readlines.py