Run Matlab code from Python with oct2py

Python can run Matlab code using GNU Octave via Oct2Py. Python transparently calls Matlab/Octave .m functions without having Matlab. oct2py uses GNU Octave to run most .m code that doesn’t call proprietary Matlab toolboxes. Shared memory (RAM) or disk (temporary file) is used to transfer data between Octave and Python.

Install

Usually Octave ≥ 4.4 is adequate for Oct2py. Newer Octave versions have improved plotting and Matlab compatibility. Here are a few different ways to install GNU Octave–pick any one way that suits you:

  • Windows installer

  • Linux (package manager): apt install octave or yum install octave

  • Linux (flatpak): install Octave via flatpak

  • Linux or MacOS (Homebrew): brew install octave

Install oct2py Python ↔ Octave module:

pip install oct2py

Note, some Octave functions require you to install their packages.

Usage

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 exectuable. It’s generally not recommended to add Octave to the system Path on Windows, as that can interfere with MinGW or MSYS2. On Windows, set user environment variable like (as appropriate for your PC)

OCTAVE_EXECUTABLE=C:/Octave/Octave-5.2.0/mingw64/bin/octave-cli.exe

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

from oct2py import Oct2Py
oc = Oct2Py()

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

You can use

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

RAM drive

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.

Examples

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.

call Matlab Engine from Python