# How to Write MatLab Functions in Python

- 2019-02-09 03:37 PM
- 96

**A tutorial on writing MatLab-like functions using the Python language and the NumPy library.**

## Overview

Recently in my work, I was re-writing algorithms developed in MatLab to Python, some functions are not so simple to adapt, especially the array functions that are called Cell Arrays.

MatLab has an API where you can call MatLab functions via Python. The idea, however, was not to use MatLab, but the same algorithm works the same way using only Python and NumPy, and the GNU Octave also has an API similar to that of MatLab.

To maintain compatibility, I have created functions with the same name that are used in MatLab that is encapsulated in a class called Precision.

## 1. Testing

Make the repository clone and follow the instructions in the README file:

Below I will show some examples, these are contained in the unit tests.

### 1.1 Start Stopwatch Time

Measuring the time spent in processing.

```
from precision import Precision
p = Precision()
p.tic()
for i in range(0, 1000): print(i)
p.toc()
```

The output will look something like this:

```
: > Elapsed time is 0:0:2 secounds.
```

### 1.2 Percentiles of a Data Set

This is used to get a percentile. In the example below, we are creating a range of ordinal dates by cutting 5% from the left and 5% from the right.

```
from datetime import datetime
from precision import Precision
p = Precision()
d = [i for i in p.dtrange(datetime(2018, 6, 12),
datetime(2059, 12, 12),
{'days':1, 'hours':2})]
x = [p.datenum(i.date()) for i in d]
x1 = p.prctile(x, 5)
x2 = p.prctile(x, 95)
r = (x2 - x1)
```

The output will look something like this:

```
5% lower: 737980.1
5% higher: 751621.9
delta: 13641.800000000047
```

### 1.3 Cell Array (cell2mat)

This converts a cell array to an ordinary array of the underlying data type.

```
from precision import Precision
p = Precision()
p.cell2mat([[1, 2], [3, 4]])
p.cell2mat('1 2; 3 4')
```

The output will look something like this:

```
matrix([[1, 2],
[3, 4]])
```

### 1.4 Cell Array (num2cell)

Convert array to cell array with consistently sized cells.

```
import numpy
from precision import Precision
p = Precision()
x = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], numpy.int64)
p.num2cell(x)
```

The output will look something like this:

```
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```

### 1.5 Concatenate Strings (strcat)

This concatenates strings horizontally using strcat.

```
import pandas
from precision import Precision
p = Precision()
df = pandas.DataFrame(data={'A': [1, 2], 'B': [3, 4]}, dtype=numpy.int8)
p.strcat(df, 'B')
```

The output will look something like this:

```
['3', '4']
```

### 1.6 Histogram (histc)

This counts the number of values in x that are within each specified bin range. The input, binranges, determines the endpoints for each bin. The output, bincounts, contains the number of elements from x in each bin.

```
import numpy
from precision import Precision
p = Precision()
v = numpy.array([[1.5, 2.0, 3], [4, 5.9, 6]], numpy.int64)
p.histc(v, numpy.amax(v) + 1)
```

The output will look something like this:

```
(array([1, 1, 1, 0, 1, 1, 1]), array([1., 1.71428571, 2.42857143,
3.14285714, 3.85714286, 4.57142857, 5.28571429, 6.]))
```

### 1.7 Unique

Looking for unique values in an array and returning the indexes, inverse, and counts.

```
import numpy
from precision import Precision
p = Precision()
x = [0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7]
p.unique(numpy.array([x]))
```

The output will look something like this:

```
array([[array([0, 1, 2, 3, 4, 5, 6, 7]),
array([[ 0, 1, 3, 4, 5, 7, 9, 10]]),
array([0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7]),
array([1, 2, 1, 1, 2, 2, 1, 3])]], dtype=object)
```

### 1.8 Overlaps

Looking for the overlays between two arrays returning the index.

```
import numpy
from precision import Precision
p = Precision()
x, y = p.overlap2d(numpy.array(['A','B','B','C']),
numpy.array(['C','A','B','C','D']))
```

The output will look something like this:

```
(array([0, 1, 2, 3]), array([1, 2, 0, 3]))
```

## Considerations

There are functions that are not exactly MatLab but will serve as support, I hope it can help someone. There is an interesting article in NumPy for users who are migrating from MatLab to Python.

### Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Learn Python by Building a Blockchain & Cryptocurrency

☞ Python and Django Full Stack Web Developer Bootcamp

☞ The Python Bible™ | Everything You Need to Program in Python

☞ Learning Python for Data Analysis and Visualization

☞ Python for Financial Analysis and Algorithmic Trading

☞ The Modern Python 3 Bootcamp

Original source: https://dzone.com