Load Octave packages in oct2py

Related: call Matlab from Python

oct2py is a wonderful way from Python to use Matlab/Octave .m code without having Matlab. As the name implies, oct2py uses GNU Octave to run most .m code out there (that doesn’t call proprietary Matlab toolboxes).

Install oct2py

Assuming you already have Octave installed, whether via

apt install octave

or via compiling Octave, then install oct2py in Python by from Terminal:

pip install oct2py

Load Octave packages from Python

When using Oct2Py, you load a package with eval like

#!/usr/bin/env python

from oct2py import Oct2Py

oc = Oct2Py()

oc.eval('pkg load signal')

b = oc.fir1(11,[0.01,0.5])

That example uses “Matlab” fir1() function from Python, perhaps to compare with scipy.signal.firwin().

Octave Packages explained

To speed up Octave loading and enhance stability and development cycles, a lot of Octave functionality is split off into packages. These package are loaded by simple pkg commands. For example the Octave signal package is loaded in a .m file by:

pkg load signal

To keep Matlab compatibility, I actually use in the .m file

try
  pkg load signal
end

This way, Matlab ignores the Octave-specific command.

Leave a Comment