使用 Oct2Py
>
您的第一个选择是使用与Octave 一起运行的 Oct2Py,这是一个可以运行 Matlab 文件和函数的免费开源程序。只需使用以下终端命令安装它:
pip3 install oct2py
然后你可以像这样从你的 Python 脚本运行 MatLab 代码:
from oct2py import Oct2Py
oc = Oct2Py()
script = "function y = myScript(x)\n" \
" y = x-5" \
"end"
with open("myScript.m","w+") as f:
f.write(script)
oc.myScript(7)
使用 MatLab
如果您想使用原始的 MatLab 引擎,您必须按照以下步骤操作:
1.安装 MatLab 库
按照this page 的说明,您首先必须通过打开 MatLab 并运行命令matlabroot 来找到您的 MatLab 根文件夹。这应该为您提供 Matlab 的根文件夹。
然后你打开你的终端(如果你使用的是Windows,你可以通过按Windows + R,然后输入cmd并按Enter。)在终端中运行以下代码:
cd matlabroot\extern\engines\python
确保将 matlabroot 替换为您刚刚找到的路径。然后你运行
python3 setup.py install
安装 MatLab Python 库。
2。使用 MatLab 库
按照this page的指示就可以了
import matlab.engine
eng = matlab.engine.start_matlab()
tf = eng.isprime(37)
print(tf)
如果您想运行entire scripts,您可以将脚本保存为当前文件夹中的 MatLab *.m 文件,然后像这样运行它们:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.myMatlabFile(nargout=0) # Expects a file named myMatlabFile.m in the same directory
您也可以从 Python 创建 MatLab 文件:
import matlab.engine
script = "b = 5;\n" \
"h = 3;\n" \
"a = 0.5*(b.* h)"
with open("myScript.m","w+") as f:
f.write(script)
eng = matlab.engine.start_matlab()
eng.myScript(nargout=0)
我希望这会有所帮助:)