14
votes

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!

1
Do you have Matlab installed on your computer? - pascscha
Yes, I have the 2016b version - Julian

1 Answers

19
votes

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 :)