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:

import scipy.io
f = scipy.io.loadmat('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"]
numpy.array(x)

Dependencies: Numpy and h5py

Leave a comment