Reading Matlab files – Structures

Suppose you have saved a structure called “data” in matlab:

% "x" and "y" are two fields in the structure "data"
data.x = linspace(1,100,100);
data.y = linspace(1,100,100);

% save a .mat file

To read “x” and “y” into python:


# import file into a dictionary
f ='matlabfile.mat')

# read in the structure
data = f['data']

# get the fields
x = data[0,0]['x']
y = data[0,0]['y']

Reading Matlab files

For this example, first create a Matlab file:

In matlab…

x = magic(200); % This creates a matrix
save('matlabfile.mat','x') % This saves the matrix in a file named matlabfile.mat

Then in python, open file with this:

f ='matlabfile.mat') # Imports file into a dictionary where the "key" is the matlab name of the variable (i.e. x) and the data is stored as the dictionary value

x = f["x"] # Makes the python variable "x" equal to the data associated with key "x" (in f)

For files saved with Matlab v7.3, use this:

import h5py
import numpy

f = h5py.File('matlabfile.mat')
x = f["x"]

Dependencies: Numpy and h5py