我正在尝试使用 Python 运行 MATLAB 代码(我使用的是 python 3.6)。
我不需要传递任何参数或获取任何输出。我只需要一行 Python 代码来运行 MATLAB 代码。
我在网上看到一些答案说使用 matlabroot
并在命令提示符下使用它来安装某种引擎但是它说我无法安装它因为我的 Python 版本不旧足够了(这没有意义)。
是否有更简单的版本或其他方法?
谢谢!
最佳答案
使用 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)
希望对您有所帮助:)
关于python - 如何从 Python 中运行 MATLAB 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406331/