matlab調用Python的.py指令檔__Python

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.