matlab自带python,如何在Python中运行MATLAB代码

I am trying to run a MATLAB code using Python (I'm using python 3.6).

I don't need to pass any arguments or get any outputs. I just need a line of code on Python that will simply run the MATLAB code.

I saw some answers online that say to use matlabroot and to use that in the command prompt to install some sort of engine but it said I couldn't install it because my Python version was not old enough (which makes no sense).

Is there an easier version or just another way to do this?

Thanks!

解决方案

Using Oct2Py

Your first option is using Oct2Py which runs with Octave, a free and opensource Program that can run Matlab files and functions. Just install it with the following Terminal command:

pip3 install oct2py

Then you can run MatLab Code from your Python script like that:

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)

Using MatLab

If you want to use the original MatLab engine you would have to follow the following steps:

1. Installing the MatLab library

Following the instructions of this page you first have to find your MatLab root folder by opening MatLab and running the command matlabroot. This should give you the root folder for Matlab.

Then you open your terminal (if you are using Windows you can do that by pressing Windows + R, then type cmd and press Enter.) In the terminal you run following code:

cd matlabroot\extern\engines\python

Make sure to replace matlabroot with the Path you just found. Then you run

python3 setup.py install

To install the MatLab Python library.

2. Using the MatLab Library

Following the instructions of this page You can then

import matlab.engine

eng = matlab.engine.start_matlab()

tf = eng.isprime(37)

print(tf)

If you want to run entire scripts, you can save your scripts as a MatLab *.m file in your current folder and run them like this:

import matlab.engine

eng = matlab.engine.start_matlab()

eng.myMatlabFile(nargout=0)

You could also create the MatLab File from Python:

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)

I hope this helps :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值