https://ww2.mathworks.cn/help/matlab/matlab_external/install-the-matlab-engine-for-python.htmlhtml
要在 Python® 會話內啓動 MATLAB® 引擎,必須先安裝 Python 包形式的引擎 API。MATLAB 提供了標準的 Python setup.py
文件,用於經過 distutils
模塊編譯和安裝引擎。您能夠使用相同的 setup.py
命令在 Windows®、Mac 或 Linux® 系統上編譯和安裝引擎。python
在安裝以前,確認您的 Python 和 MATLAB 配置。api
您的系統具備受支持的 Python 版本和 MATLAB R2014b 或更新版本。要檢查您的系統上是否已安裝 Python,請在操做系統提示符下運行 Python。瀏覽器
將包含 Python 解釋器的文件夾添加到您的路徑(若是還沒有在該路徑中)。async
找到 MATLAB 文件夾的路徑。啓動 MATLAB,並在命令行窗口中鍵入 matlabroot
。複製 matlabroot
所返回的路徑。函數
要安裝引擎 API,請在操做系統提示符下執行如下命令,其中 matlabroot
是 MATLAB 文件夾的路徑。您可能須要管理員權限才能執行這些命令。或者,使用在非默認位置安裝用於 Python 的 MATLAB 引擎 API 中所述的非默認選項之一。ui
在 Windows 系統中 -spa
cd "matlabroot\extern\engines\python" python setup.py install
在 Mac 或 Linux 系統中 -操作系統
cd "matlabroot/extern/engines/python" python setup.py install
您能夠直接調用任何 MATLAB® 函數並將結果返回到 Python®。例如,要肯定某個數是否爲質數,請使用該引擎調用 isprime
函數。命令行
import matlab.engine eng = matlab.engine.start_matlab() tf = eng.isprime(37) print(tf)
True
當使用引擎調用函數時,默認狀況下該引擎會返回單個輸出參數。若是您知道函數可能返回多個參數,請使用 nargout
參數指定輸出參數的數量。
要肯定兩個數的最大公分母,請使用 gcd
函數。設置 nargout
以從 gcd
返回三個輸出參數。
import matlab.engine eng = matlab.engine.start_matlab() t = eng.gcd(100.0,80.0,nargout=3) print(t)
(20.0, 1.0, -1.0)
有些 MATLAB 函數不會返回任何輸出參數。若是函數不返回任何參數,則將 nargout
設爲 0。
經過 Python 打開 MATLAB 幫助瀏覽器。
import matlab.engine eng = matlab.engine.start_matlab() eng.doc(nargout=0)
MATLAB doc
函數將打開瀏覽器,但不會返回輸出參數。若是您沒有指定 nargout=0
,引擎將報告錯誤。
要中止執行 MATLAB 函數,請按 Ctrl+C。控制權將返回給 Python。
This example shows how to call the MATLAB® sqrt
function asynchronously from Python® and retrieve the square root later.
The engine calls MATLAB functions synchronously by default. Control returns to Python only when the MATLAB function finishes. But the engine also can call functions asynchronously. Control immediately returns to Python while MATLAB is still executing the function. The engine stores the result in a Python variable that can be inspected after the function finishes.
Use the async
argument to call a MATLAB function asynchronously.
import matlab.engine eng = matlab.engine.start_matlab() future = eng.sqrt(4.0,async=True) ret = future.result() print(ret)
2.0
Use the done
method to check if an asynchronous call finished.
tf = future.done() print(tf)
True
To stop execution of the function before it finishes, call future.cancel()
.