为什么我不能得到这个numpy数组的形状?

时间:2017-05-09 16:26:19

标签: python arrays matlab numpy

我正在使用scipy.io导入matlab文件,并尝试查找其尺寸。看来,即使文件被加载到python中,它也无法给出维度。这是为什么?以及如何解决这个问题?

>>> import scipy.io
>>> pref_mat = scipy.io.loadmat('pref_mat_loc.mat')
>>> R=pref_mat
>>> import numpy
>>> R=numpy.array(R)
>>> len(R)
0
>>> R # We see that the first line of the file is getting printed, means the file has been loaded.

array({'pref_mat': array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16), '__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Mon May 08 23:42:05 2017', '__version__': '1.0', '__globals__': []}, dtype=object)

>>> len(R.shape) # But it appears here as though R is empty
0
>>> R.shape # As does here
()

1 个答案:

答案 0 :(得分:2)

pref_mat返回的

loadmat是一本字典。您已将其包装在数组R中。我可以将pref_mat的内容推断为R的{​​}部分:

{'pref_mat': array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16), 
'__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Mon May 08 23:42:05 2017', 
'__version__': '1.0', 
'__globals__': []}

所以你感兴趣的数组是

R = pref_mat['pref_mat']

R应该具有您想要的形状和类型。虽然在摘要视图中我只看到0&#39。

如果MATLAB保存了单元格或构造了“对象”的嵌套。类型数组会变得更复杂。