【问题标题】:Accessing array contents inside .mat file in python在python中访问.mat文件中的数组内容
【发布时间】:2018-09-08 00:24:16
【问题描述】:

我想阅读http://www.eigenvector.com/data/tablets/index.html 上的 .mat 文件。要访问此文件中的数据,我正在尝试以下操作:

import scipy.io as spio
import numpy as np
import matplotlib.pyplot as plt
mat = spio.loadmat('nir_shootout_2002.mat')

# http://pyhogs.github.io/reading-mat-files.html
def print_mat_nested(d, indent=0, nkeys=0):
    if nkeys>0:
        d = {k: d[k] for k in d.keys()[:nkeys]}
    if isinstance(d, dict):
        for key, value in d.iteritems():
            print '\t' * indent + 'Key: ' + str(key)
            print_mat_nested(value, indent+1)

    if isinstance(d,np.ndarray) and d.dtype.names is not None:
        for n in d.dtype.names:
            print '\t' * indent + 'Field: ' + str(n)
            print_mat_nested(d[n], indent+1)

print_mat_nested(mat, nkeys=1)

上面的命令显示字典中的第一个键是“validate_1”,它有一个字段“data”。要访问此字段,我尝试:

t = mat['validate_1']
print(t['data'])

它打印一个数组,但是当我使用np.shape(t['data']) 时,它只返回 (1,1) 而数据似乎更大。我不确定如何访问 t['data'] 中的数组。

感谢您的帮助。

【问题讨论】:

    标签: matlab numpy file-io scipy mat-file


    【解决方案1】:

    我发现以下工作:

    t = mat['validate_1']['data'][0,0]
    print(np.shape(t))
    

    它返回 t 是一个形状为 (40,650) 的数组。

    【讨论】:

    • MATLAB 让一切都变成二维的。因此,最终形状为 (1,1) 的单个项目矩阵或单元格(除非您使用 squeezeme)。但cellstructs 也可能显示为object dtype 数组。因此,可能需要索引和/或item() 来剥离该层。
    • 如果我在读取 .mat 文件时使用 squeeze_me=True,我正在使用的解决方案不起作用。您能否建议在这种情况下如何使用 `item()' 或索引来访问数组?
    • x.item() 适用于任何单个元素数组。 x[()] 使用 0d 数组。
    猜你喜欢
    • 2011-09-10
    • 2013-03-08
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多