DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Write MatLab Functions in Python

How to Write MatLab Functions in Python

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

Ederson Corbari user avatar by
Ederson Corbari
·
Feb. 07, 19 · Tutorial
Like (2)
Save
Tweet
Share
8.88K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • https://github.com/edersoncorbari/mat2py

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.

  • NumPy for MATLAB© Users
Matlab Python (language) Data structure

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Using JSON Web Encryption (JWE)
  • Beginners’ Guide to Run a Linux Server Securely
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • Kubernetes vs Docker: Differences Explained

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: