How to import a (MATLAB) .mat file into Python?
Post date: Aug 30, 2012 4:01:06 AM
Q: How to import a (MATLAB) .mat file into Python?
A: The .mat file will be imported into Python in the form of dictionary, using the function loadmat
in the package scipy.io
.
In this example below, we import easymatfile.mat
into dictionary x
.
'''This code shows how to import .mat file (MATLAB format) into dictionary using scipy.io'''
# First we will import the scipy.io
import scipy.io
# load .mat file into dictionary x
x = scipy.io.loadmat('/home/bot/Dropbox/course_work/python_study/fMRI_basic/easymatfile.mat')
# easymatfile.mat contains 3 matlab variables
# a: [10x30]
# b: [20x100]
# c: [1x1]
# in order to get a, b and c we say
pyA = x['a']
pyB = x['b']
pyC = x['c']
# Now we want plot the figures
from pylab import *
from matplotlib import *
matshow(pyA,1)
matshow(pyB,2)
matshow(pyC,3)
# Now, we will show all three figures
show()
In IDLE workspace, you will find that x is a dictionary with 'a', 'b' and 'c' and the keys. Also, you will some additional keys '__header__', '__globals__' and '__version__'.
>>> x
{'a': some 10x30 array ,
'c': array([[ 1.2]]),
'b': some 20 x 100 array,
'__header__': 'MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Wed Aug 29 20:19:01 2012',
'__globals__': [],
'__version__': '1.0'}