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
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就可以用這個函數調用python指令碼了。 下面就來個調用python指令碼matlab_readlines.py(儲存在matlab目前的目錄)的例子
import sysdef 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 "+fnameif '__main__'==__name__: if len(sys.argv)<2: print 'No file specified.' sys.exit() else: readLines(sys.argv[1])這個指令碼用來讀取一個文字檔,並產生Matlab風格的cell數組的定義字串,每個單元為文本的一行。 放了一個測試用的文字檔test.txt在Matlab的Current Directory中,內容如下:
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