Reading mat files - Python

Reading mat files - Python

Here are examples of how to read two variables lat and lon from a mat file called “test.mat”.

1. Matlab up to 7.1

mat files created with Matlab up to version 7.1 can be read using the mio module part of scipy.io. Reading structures (and arrays of structures) is supported, elements are accessed with the same syntax as in Matlab: after reading a structure called e.g. struct, its lat element can be obtained with struct.lat, or struct.__getattribute__('lat') if the element name comes from a string.

#!python
#!/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']

2. 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. Reading Matlab structures in mat files does not seem supported at this point.

#!python
#!/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)[:]

References

https://yongqiang.blog.csdn.net/
https://scipy-cookbook.readthedocs.io/items/Reading_mat_files.html
https://github.com/scipy/scipy-cookbook

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yongqiang Cheng

梦想不是浮躁,而是沉淀和积累。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值