官網鏈接:
https://ww2.mathworks.cn/help/matlab/matlab_external/call-user-script-and-function-from-python.html?lang=en
https://ww2.mathworks.cn/help/matlab/matlab_external/install-the-matlab-engine-for-python.html
安裝用於 Python 的 MATLAB 引擎 API
要在 Python® 會話內啟動 MATLAB® 引擎,必須先安裝 Python 包形式的引擎 API。MATLAB 提供了標准的 Python setup.py 文件,用於通過 distutils 模塊編譯和安裝引擎。您可以使用相同的 setup.py 命令在 Windows®、Mac 或 Linux® 系統上編譯和安裝引擎。
在安裝之前,確認您的 Python 和 MATLAB 配置。
-
您的系統具有受支持的 Python 版本和 MATLAB R2014b 或更新版本。要檢查您的系統上是否已安裝 Python,請在操作系統提示符下運行 Python。
-
將包含 Python 解釋器的文件夾添加到您的路徑(如果尚未在該路徑中)。
-
找到 MATLAB 文件夾的路徑。啟動 MATLAB,並在命令行窗口中鍵入
matlabroot。復制matlabroot所返回的路徑。
要安裝引擎 API,請在操作系統提示符下執行以下命令,其中 matlabroot 是 MATLAB 文件夾的路徑。您可能需要管理員權限才能執行這些命令。或者,使用在非默認位置安裝用於 Python 的 MATLAB 引擎 API 中所述的非默認選項之一。
-
在 Windows 系統中 -
cd "matlabroot\extern\engines\python" python setup.py install
-
在 Mac 或 Linux 系統中 -
cd "matlabroot/extern/engines/python" python setup.py install
從 MATLAB 函數返回輸出參數
您可以直接調用任何 MATLAB® 函數並將結果返回到 Python®。例如,要確定某個數是否為質數,請使用該引擎調用 isprime 函數。
import matlab.engine eng = matlab.engine.start_matlab() tf = eng.isprime(37) print(tf)
True
從 MATLAB 函數返回多個輸出參數
當使用引擎調用函數時,默認情況下該引擎會返回單個輸出參數。如果您知道函數可能返回多個參數,請使用 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 函數返回任何輸出參數
有些 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。
Call MATLAB Functions Asynchronously from 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().
