matlab呼叫Python的.py指令碼檔案
阿新 • • 發佈:2019-02-11
matlab把所有引數輸出到一個檔案裡,然後用system命令調python指令碼。python指令碼讀檔案做計算結果再寫檔案。最後matlab再讀檔案得到結果。假設python指令碼的用法是:
python xxx.py in.txt out.txt
則matlab呼叫的命令:
[status, cmdout] =
system
(
'python xxx.py in.txt out.txt'
)
Matlab的system函式用來向作業系統傳送一條指令,並得到控制檯的輸出,可以直接將控制檯的輸出在Command Window打印出來,或者儲存在變數中。 與system類似的還有dos函式和unix函式,我覺得它們都是對system函式的一種包裝,而Matlab的system函式也許是對C的庫函式system的包裝。
先編寫一個呼叫Python指令碼的matlab程式即python.m
就可以用這個函式呼叫python指令碼了。 下面就來個呼叫python指令碼matlab_readlines.py(儲存在matlab當前目錄)的例子function [result status] = python(varargin) % call python %命令字串 cmdString='python'; for i = 1:nargin thisArg = varargin{i}; if isempty(thisArg) | ~ischar(thisArg) error(['All input arguments must be valid strings.']); elseif exist(thisArg)==2 %這是一個在Matlab路徑中的可用的檔案 if isempty(dir(thisArg)) %得到完整路徑 thisArg = which(thisArg); end elseif i==1 % 第一個引數是Python檔案 - 必須是一個可用的檔案 error(['Unable to find Python file: ', thisArg]); end % 如果thisArg中有空格,就用雙引號把它括起來 if any(thisArg == ' ') thisArg = ['"', thisArg, '"']; end % 將thisArg加在cmdString後面 cmdString = [cmdString, ' ', thisArg] end %傳送命令 [status,result]=system(cmdString); end
這個指令碼用來讀取一個文字檔案,並生成Matlab風格的cell陣列的定義字串,每個單元為文字的一行。 放了一個測試用的文字檔案test.txt在Matlab的Current Directory中,內容如下: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 is test.txt
It can help you test python.m
and matlab_readlines.py
測試:
在Matlab的Command Window中輸入:
>> 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