Python can run Matlab code using GNU Octave via
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.
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:
Linux (package manager):
apt install octaveor
yum install octave
Linux (flatpak): install Octave via flatpak
Linux or MacOS (Homebrew):
brew install octave
oct2py Python ↔ Octave module:
pip install oct2py
Note, some Octave functions require you to install their packages.
import oct2py does not find Octave or finds the wrong Octave, set the environment variable
OCTAVE_EXECUTABLE with the full path to the
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)
.m functions are transparently used from Python like:
from oct2py import Oct2Py oc = Oct2Py() oc.functionname(arg1,arg2,...)
You can use
- user functions (
.mfiles you create)
- builtin functions e.g.
- package functions e.g.
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.
- create/reuse an
.mfunction with the appropriate input & output variables.
- call this
.mfunction using Oct2Py from Python
For example, Matlab/Octave
fir1() is compared in
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.