python 读取-v7.3版本的.mat文件

一 :普通版本的.mat文件

使用sicpy.io即可.sicpy.io提供了两个函数loadmat和savemat,非常方便.

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import scipy.io as sio  

  2. import numpy as np  

  3. #matlab文件名    

  4. data=sio.loadmat('test.mat')    

  5. xi=data['xi']  

  6. yi=data['yi']  

  7. ui=data['ui']  

  8. vi=data['vi']  

二:普通的v7.3版本.mat文件

Python中读取MATLAB的.mat文件一般使用scipy,但是scipy不支持-v7.3版本的.mat文件(-v7.3版本能支持较大的文件);因此使用h5py进行读取。

在使用h5py之前首先要安装h5py,具体的安装过程可看安装博文:http://blog.csdn.NET/linmingan/article/details/50736300

(anaconda 自带)


利用h5py读取-v7.3的.mat文件:

import h5py

dict_data = h5py.File('***.mat')    #在Python中读取的.mat为字典格式

array_data = dict_data['array_name']  

其中的array_name为在保存为.mat之前的真正变量名,如 MATLAB命令:save ***.mat array_name -v7.3

Python读取并解析`.mat`文件数据,有不同的方法,以下为您详细介绍: ### 使用`scipy.io.loadmat` 当`.mat`文件为经典格式(非v7.3版本,即非HDF5格式)时,可使用`scipy.io.loadmat`函数。 示例代码如下: ```python import scipy.io # 加载.mat文件 mat_file = scipy.io.loadmat('example.mat') # 访问文件中的变量 A = mat_file['A'] B = mat_file['B'] C = mat_file['C'] print(A) print(B) print(C) ``` ### 使用`h5py` 对于v7.3版本(HDF5格式)的`.mat`文件,需要使用`h5py`库来读取。 示例代码如下: ```python import h5py # 打开.mat文件 with h5py.File('example.mat', 'r') as f: # 访问文件中的变量 A = f['A'][:] B = f['B'][:] C = f['C'][:] print(A) print(B) print(C) ``` ### 处理复杂数据结构 当`.mat`文件中存放的是`cell`数据,且`cell`数据中又分为多个`cell`时,需要进一步处理。 示例代码如下: ```python import h5py def read_cell_data(f, cell_ref): cell_data = [] for ref in cell_ref: if isinstance(ref, h5py.Reference): obj = f[ref] if isinstance(obj, h5py.Dataset): cell_data.append(obj[:]) elif isinstance(obj, h5py.Group): cell_data.append(read_cell_data(f, obj['data'])) return cell_data # 打开.mat文件 with h5py.File('example.mat', 'r') as f: # 假设cell数据存储在 'cell_data' 变量中 cell_ref = f['cell_data'][:] cell_data = read_cell_data(f, cell_ref) print(cell_data) ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值