由于我想用python版Gurobi跑一个在Matlab上神经网络的暴力,需要用Python调用Matlab中的函数,但Matlab目前并不能很好的原生适配M1芯片,以下为我的解决方法
- 安装
matlab.engine
库- 首先需要确认Python的版本,目前
matlab.engine
库最高支持Python3.9 - 使用Python3.10会报错
- 该库不能直接用pip安装,安装所需的py文件在matlab目录下
- 先cd到matlab根目录下
-
cd /Applications/MATLAB_R2022a.app cd extern/engines/python python3 setup.py install
- 首先需要确认Python的版本,目前
- 运行代码
python代码
import matlab.engine
def add(a, b):
eng = matlab.engine.start_matlab()
rst = eng.add(a, b)
print(rst)
if __name__ == '__main__':
add(3, 5)
matlab代码
function y = add(a, b)
y = a + b;
end
特别注意:
如果直接运行会出现下面报错提醒:
ImportError: dlopen(/Applications/MATLAB_R2022a.app/extern/engines/python/../../../extern/bin/maci64/matlabmultidimarrayforpython.cpython-39-darwin.so, 0x0002): tried: '/Applications/MATLAB_R2022a.app/extern/engines/python/../../../extern/bin/maci64/matlabmultidimarrayforpython.cpython-39-darwin.so' (mach-o file, but is an incompatible architecture (have (x86_64), need (arm64e))), '/Applications/MATLAB_R2022a.app/extern/bin/maci64/matlabmultidimarrayforpython.cpython-39-darwin.so' (mach-o file, but is an incompatible architecture (have (x86_64), need (arm64e)))
解决方案:
在终端中运行,前面加上arch -x86_64
arch -x86_64 python3 main.py
就可以正常跑出结果了
arch -x86_64命令的意思大概是让python以x86指令集跑这个代码,具体明天再查