Skip to content

MATLAB tricks in python

Marinna Martini edited this page Dec 17, 2019 · 2 revisions

Have you got data in MATLAB .mat files you want to use in python?

A simple loading and plotting example

How to load a simple time series, including MATLAB's time number:

from scipy.io import loadmat
import matplotlib.pyplot as plt
%matplotlib inline
from datetime import datetime
from datetime import timedelta
import numpy as np

matfile = r'yourmatfilehere.mat'
matdata = loadmat(lombmatfile)

def matlab2datetime(matlab_datenum):
    day = datetime.fromordinal(int(matlab_datenum))
    dayfrac = timedelta(days=matlab_datenum%1) - timedelta(days=366)
    return day + dayfrac

# my data is arranged in MATLAB as several time series within the struct Lomb, that
# also includes the time stamps as Lomb.tm in MATLAB.  
# loadmat loads in data that may be in a struct as an array of arrays.
# This for loop gets at the data in a way that python can use it.
tm = []
for item in enumerate(matdata['Lomb']['tm'][0][0]):
    tm.append(matlab2datetime(item[1][0]))

fig, ax = plt.subplots(2,1,figsize=(15,4))
ax[0].plot(matdata['Lomb']['Hs'][0][0], label='MATLAB Lomb Hs')
ax[0].set_title('plotted against file index')
ax[0].legend()
ax[1].plot(tm,matdata['Lomb']['Hs'][0][0], label='MATLAB Lomb Hs')
ax[1].set_title('plotted against MATLAB time stamps in file')
ax[1].legend()

Here's what those nested arrays created from a MATLAB struct look like:

# the tricky part here is that the data is returned as an array 
# embeded in an array, and so each value is its own array
# and this is because I stored the data as a struct
print(matdata['Lomb']['tm'][0][0].shape)
print(len(matdata['Lomb']['tm'][0][0]))
print(matdata['Lomb']['tm'][0][0][0])
print(matdata['Lomb']['tm'][0][0][0][0])
print(type(matdata['Lomb']['tm'][0][0][0][0]))

(641, 1)
641
[736733.41622685]
736733.4162268519
<class 'numpy.float64'>

The gist is here: https://gist.github.com/mmartini-usgs/982c3de76813ad09591137feaf4fa8fc

References: https://stackoverflow.com/questions/13965740/converting-matlabs-datenum-format-to-python

Clone this wiki locally