codemagic
  • Home
  • About.me
  • Resume
  • Blog

.Mat files  - reading  and  creating  in  python

1/20/2014

0 Comments

 
There are several versions of the .mat files v7.3, v7, v6, v4.  A significant difference between each of the version is the way the data is stored inside them.
      -v4 ,-v6  : In these versions  Matlab allowed storing a variety of structures like sparse arrays , two dimensional double  and extended its varied structure storage.
      -v7  : From this version Matlab started compressing the data. This compression and decompression  slowed down the loading and saving process but used very less space in the disk
      -v7.3  : In this version Matlab started to use HDF5 format of storing the data in a compressed chunks. The time required to load the data differed by the way the data is stored among the chunks
you can check this for detailed information regarding the versions and their features list.

you can create any version mat file using the "save" command in Matlab 

save(filename,variables,version) saves to the MAT-file version specified by version. The variables argument is optional, as described above.

eg,
A = rand(5); 
B = magic(10); 
save('example.mat','A','B','-v7.3')

due to the varied versions of mat file. Reading a mat file became a complicated task to carryout. 
Here I would describe two ways you could read and create a mat file in python.

Matlab -v4. -v6,-v7
Need to import scipy.io

loadmat(file_name[, mdict, appendmat])   Load MATLAB file
savemat(file_name, mdict[, appendmat, ...])  Save a dictionary of names and arrays into a MATLAB-style .mat file.


eg,
#!/usr/bin/env python 
from scipy.io import loadmat 
x = loadmat('test.mat') 
lon = x['lon'] 
lat = x['lat'] 
# one-liner to read a single variable 
lon = loadmat('test.mat')['lon']
x['lon']='clon'
savemat('changetest.mat',x)

Matlab -v7.3
since the data is stored in the form of HDF5 chunks. we need to install python-tables or python-h5py package. which allows python to access HDF5 chunks. you could use apt-get  or download the files from these websites.
Pytables
h5py

eg
#!/usr/bin/env python 
import tables
file = tables.openFile('test.mat') 
lon = file.root.lon[:] 
lat = file.root.lat[:] 
# Alternate syntax if the variable name is in a string 
varname = 'lon' 
lon = file.getNode('/' + varname)[:]

additional references
http://wiki.scipy.org/Cookbook/Reading_mat_files
http://docs.scipy.org/doc/scipy/reference/tutorial/io.html
http://www.mathworks.com/help/matlab/import_export/mat-file-versions.html


0 Comments



Leave a Reply.

    Author

    Kaushal Bondada

    Archives

    January 2014

    Categories

    All
    C++
    Latex
    Machine Learning
    Matlab
    Python
    Vim

    RSS Feed

Powered by Create your own unique website with customizable templates.