之前在博客園上總結(jié)的筆記,最近需要翻了出來,共享在簡書上。
update 2016.10.4
轉(zhuǎn)移到另一個環(huán)境使用mlabwrap的時候遇到很多問題。首先是mlabwrap要root權(quán)限,其次是import的時候提示`GLIBCXX_3.4.15' not found為此更新了GCC版本,最后在調(diào)用函數(shù)的時候又報錯,眼瞎到?jīng)]有理解是matlab腳本的錯誤,搜mlab的操作試了半天。經(jīng)過對比python-matlab-bridge,我還是習(xí)慣用mlabwrap,前者啟動需要權(quán)限,啟動后機(jī)器就不能正常打印輸出了,不知道是什么鬼。。
環(huán)境:matlab2014b,mac os,python 2.7
windows用戶可以用win32com,COM只適用于WINDOWS系統(tǒng),這里沒有嘗試。
如果是執(zhí)行簡單的命令,可以用matlab2014b提供的引擎,我的在/Applications/MATLAB_R2014b.app/extern/engines/python。
Matlab Engine for Python
Call Matlab Function from Python
Step 1: Installation
Install with Administrator Privileges
cd "matlabroot\extern\engines\python"
python setup.py install
Install without Administrator Privileges
cd "matlabroot\extern\engines\python"
python setup.py build --build-base builddir install --install-base installdir
Include 'installdir' in the search path for Python packages
Add 'installdir' to the PYTHONPATH environment variavle
Step 2: Using Matlab Engine
Start and quit
import matlab.engine
eng = matlab.engine.start_matlab()
eng.quit()
Call Matlab Functions:
Just call with form eng.xxx()
the function xxx should in the namespace of matlab.
Asynchronously Call
import matlab.engine
eng = matlab.engine.start_matlab()
future = eng.sqrt(4.0,async=True)
ret = future.result()
print(ret)
WorkSpace Usage:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.workspace['y'] = x
a = eng.eval('sqrt(y)')
print(a)
Skills for unsupported features in python
eng.eval()
import matlab.engine
eng = matlab.engine.start_matlab()
eng.eval("T = readtable('patients.dat');",nargout=0)
Plot With Matlab:
import matlab.engine
eng = matlab.engine.start_matlab()
data = eng.peaks(100)
eng.mesh(data)
- python直接調(diào)用執(zhí)行matlab,現(xiàn)有很多工具:
3.1. pymat
沒有python2.7的支持
3.2. pymat2
在pymat基礎(chǔ)上改良過的。
3.3. mlabwrap
http://mlabwrap.sourceforge.net/
需要用root權(quán)限。最初安裝不成功,報OSError: [Errno 2] No such file or directory,應(yīng)該是找不到MATLAB2014b的路徑,更改PATH加上MATLAB的安裝目錄后成功(在setup.py中更改安裝參數(shù)應(yīng)該也可以,沒有嘗試)。export PATH=/Applications/MATLAB_R2014b.app/bin:$PATH
from mlabwrap import mlab的時候又報import mlabraw引入不成功,google之后發(fā)現(xiàn)export DYLD_LIBRARY_PATH=/Applications/MATLAB_R2014b.app/bin/maci64:$DYLD_LIBRARY_PATH即可,
這里runmodel.m文件內(nèi)容是Function result = runmodel() ..... END
調(diào)用方式為mlab.runmodel()
http://sourceforge.net/p/mlabwrap/mailman/message/26145026/
傳入?yún)?shù):
mlab.runmodel('[1,2,3,4,5]',...)注意參數(shù)必須為字符串,python會將其轉(zhuǎn)換為各種形式。
3.4. mlab
貌似在mac上不穩(wěn)定,執(zhí)行不了后就放棄了。
3.5. python-matlab-bridge
https://github.com/jaderberg/python-matlab-bridge
only work on unix, and is based on TCP transmission while messages are decoded in JSON format。
3.6. Nipype
http://nipy.sourceforge.net/nipype/api/generated/nipype.interfaces.matlab.html