# Run Matlab code from Python with oct2py

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.

## Install

- Install GNU Octave:
- Linux:
`apt install octave`

- Mac:
`brew install octave`

- Windows installer
- BSD:
`pkg install octave`

- Linux:
- Install
`oct2py`

:`python -m pip install oct2py`

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

## Usage

Matlab/Octave `.m`

functions are transparently used from Python like:

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

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.

## Examples

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()`

compared
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.

## Leave a comment