Python can run Matlab code using
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
oct2py Python ↔ Octave module:
pip install oct2py
Some Octave functions require package install.
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.
.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.
- 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.
Related: call Matlab Engine from Python