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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s