Accessing array contents inside .mat file in python

守給你的承諾、 提交于 2020-01-03 05:51:04

问题


I want to read a .mat file available at http://www.eigenvector.com/data/tablets/index.html. To access the data inside this file, I am trying the follwing:

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)

Above command shows that the first key in the dictionary is "validate_1" and it has a field "data". To access this field, I try:

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

It prints an array but when I use np.shape(t['data']), it just returns (1,1) whereas the data seems to be larger. I am not sure how to access array inside t['data'].

Thanks for the help.


回答1:


I found that following works:

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

It returns that t is an array of shape (40,650).



来源:https://stackoverflow.com/questions/49549382/accessing-array-contents-inside-mat-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!