Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read .mat files in Python

Is it possible to read binary MATLAB .mat files in Python?

I've seen that SciPy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed SciPy version 0.7.0, and I can't find the loadmat() method.

like image 201
Gilad Naor Avatar asked May 17 '09 12:05

Gilad Naor


People also ask

Can we read .MAT file in Python?

Matlab 7.3 and greater Beginning at release 7.3 of Matlab, mat files are actually saved using the HDF5 format by default (except if you use the -vX flag at save time, see in Matlab). These files can be read in Python using, for instance, the PyTables or h5py package.

How do I read a .MAT dataset in Python?

Use the mat4py Module to Read mat Files in Python The loadmat() function reads MATLAB files and stores them in basic Python structures like a list or a dictionary and is similar to the loadmat() from scipy.io .

How do I read a .MAT file?

How to Open an MAT File. MAT files that are Microsoft Access Shortcut files can be created by dragging a table out of Access and to the desktop or into another folder. Microsoft Access needs to be installed in order to use them. MATLAB from MathWorks can open MAT files that are used by that program.


2 Answers

An import is required, import scipy.io...

import scipy.io mat = scipy.io.loadmat('file.mat') 
like image 50
Gilad Naor Avatar answered Sep 28 '22 08:09

Gilad Naor


Neither scipy.io.savemat, nor scipy.io.loadmat work for MATLAB arrays version 7.3. But the good part is that MATLAB version 7.3 files are hdf5 datasets. So they can be read using a number of tools, including NumPy.

For Python, you will need the h5py extension, which requires HDF5 on your system.

import numpy as np import h5py f = h5py.File('somefile.mat','r') data = f.get('data/variable1') data = np.array(data) # For converting to a NumPy array 
like image 27
vikrantt Avatar answered Sep 28 '22 08:09

vikrantt