Read .mat files in Python

2019-01-01 04:26发布

Does anyone have successful experience reading 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)

8条回答
君临天下
2楼-- · 2019-01-01 05:16

There is a nice package called mat4py which can easily be installed using

pip install mat4py

It is straightforward to use (from the website):

Load data from MAT-file

The function loadmat loads all variables stored in the MAT-file into a simple Python data structure, using only Python’s dict and list objects. Numeric and cell arrays are converted to row-ordered nested lists. Arrays are squeezed to eliminate arrays with only one element. The resulting data structure is composed of simple types that are compatible with the JSON format.

Example: Load a MAT-file into a Python data structure:

data = loadmat('datafile.mat')

The variable data is a dict with the variables and values contained in the MAT-file.

Save Python data structure to a MAT-file

Python data can be saved to a MAT-file, with the function savemat. Data has to be structured in the same way as for loadmat, i.e. it should be composed of simple data types, like dict, list, str, int and float.

Example: Save a Python data structure to a MAT-file:

savemat('datafile.mat', data)

The parameter data shall be a dict with the variables.

查看更多
还给你的自由
3楼-- · 2019-01-01 05:17

Neither scipy.io.savemat, nor scipy.io.loadmat work for matlab arrays --v7.3. But the good part is that matlab --v7.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 numpy array
查看更多
ら面具成の殇う
4楼-- · 2019-01-01 05:18

I've screwed half an hour even after reading the answers. Hope this answer helps

First save the mat file as

save('test.mat','-v7')

After that in Python use the usual loadmat

import scipy.io as sio
test = sio.loadmat('test.mat')
查看更多
浪荡孟婆
5楼-- · 2019-01-01 05:19

Reading the file

import scipy.io
mat = scipy.io.loadmat(file_name)

Insecting the type of mat variable

print(type(mat))
#OUTPUT - <class 'dict'>

The keys inside the dictionary are matlab variables and the values are the objects assigned to those variables.

查看更多
爱死公子算了
6楼-- · 2019-01-01 05:20

Silly me. Forgot to import io...

import scipy.io
mat = scipy.io.loadmat('file.mat')
查看更多
低头抚发
7楼-- · 2019-01-01 05:24

for high dimensional data, mat4py package works better:

from mat4py import loadmat
data = loadmat('datafile.mat')
查看更多
登录 后发表回答