Run Matlab code from Python with oct2py

1 minute read

Related: call Matlab Engine from Python

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 ↔ Python.


  1. Install GNU Octave:
    • Linux: apt install octave
    • Mac: brew install octave
    • Windows installer
    • BSD: pkg install octave
  2. Install oct2py:
    python -m pip install oct2py

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


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

from oct2py import Oct2Py
oc = Oct2Py()


You can use

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

Oct2Py 3.9.0 is working for me, but the latest Oct2Py 4.0 seems broken. Try pip install oct2py==3.9 if you have problems for now.


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() compared with scipy.signal.firwin().

A simpler Python script example is:

from oct2py import Oct2Py


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

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

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

Leave a Comment