## 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.
There are several ways to install GNU Octave

Install `oct2py`

Python ↔ Octave module:

```
pip install oct2py
```

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

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 executable.
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:

```
OCTAVE_EXECUTABLE=%MINGWROOT%/bin/octave-cli.exe
```

Matlab/Octave `.m`

functions are transparently used from Python like:

```
from oct2py import Oct2Py
oc = Oct2Py()
oc.functionname(arg1,arg2,...)
```

Now one can use from Python via oct2py:

- user functions (
`.m`

files you create) - builtin functions e.g.
`svd()`

- package functions e.g.
`signal`

`fir1()`

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
`.m`

function with the appropriate input & output variables. - 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.

Related: call Matlab Engine from Python