Run Matlab code from Python with oct2py

Python can run Matlab code using GNU Octave via Oct2Py. Python transparently calls Matlab/Octave “.m” functions using GNU Octave instead of Matlab. oct2py uses GNU Octave to run most “.m” code that’s compatible with the GNU Octave version installed. Shared memory (RAM) or disk (temporary file) is used to transfer data between Octave and Python. There are several ways to install GNU Octave

Install oct2py Python ↔ Octave module:

pip install oct2py

Some Octave functions require package install.

If import oct2py does not find Octave or finds the wrong Octave, set the environment variable OCTAVE_EXECUTABLE with the full path to the Octave executable. It’s generally not recommended to add Octave to the system Path on Windows, as that can interfere with MinGW or MSYS2.

Matlab/Octave .m functions are transparently used from Python like:

from oct2py import Oct2Py
oc = Oct2Py()

oc.functionname(arg1,arg2,...)

Python via oct2py can use:

  • user functions (".m" files you create)
  • builtin functions e.g. svd()
  • package functions e.g. signal fir1()

Oct2Py can be greatly sped up by using a RAM drive (tmpfs) instead of the system temporary directory. This may be accomplished by:

from oct2py import Oct2Py
oc = Oct2Py(temp_dir='/run/shm')

oc.functionname(arg1,arg2,...)

Of course, replace /run/shm with your RAM drive location.

Advanced Octave functionality is split off into packages to:

  • speed up Octave startup
  • enhance stability and development cycles

Thus you’ll see pkg load ... commands where appropriate.

  1. create/reuse an .m function with the appropriate input & output variables.
  2. call this .m function using Oct2Py from Python

For example, Matlab/Octave fir1() is compared in tests/test_oct2py.py with scipy.signal.firwin().

A simpler Python script example is:

from oct2py import Oct2Py

k=5
p=0.2

with Oct2Py() as oc:
    oc.eval('pkg load signal')
    bmat = oc.fir1(k,p)
print(bmat)
# %%
import scipy.signal

bpy = scipy.signal.firwin(k+1,p)
print(bpy)

For your own .m files, simply call the functions with input/output arguments as in the oc.fir1() line of this example.


Related: call Matlab Engine from Python