10

Here is an minimal example of the error I get. If I understood the documentation correctly, this should be working, but it seems I did not.

a={}
a['test1']=1
a['test2']=2
a['test3']=3
import scipy.io as io
io.savemat('temp',{'a':a})
b = io.loadmat('temp')
b['a'].keys()

Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'keys'
Amro
  • 123,847
  • 25
  • 243
  • 454
Framester
  • 33,341
  • 51
  • 130
  • 192

2 Answers2

11

You seem to be operating under the assumption that scipy.io.savemat is intended to be able to save a standard dictionary. I don't believe that is the case. The dictionary argument holds the names of numpy arrays which are written out into the Matlab file. So you can do something like this

import scipy.io as io
import numpy as np

y1=np.array([1,2,3,4])
y2=np.array([10,20,30,40])
y3=np.array([100,200,300,400])

a={}
a['test1']=y1
a['test2']=y2
a['test3']=y3
io.savemat('temp',a)
b = io.loadmat('temp')

print b['test1']
print b['test2']
print b['test3']

which gives:

[[1]
 [2]
 [3]
 [4]]
[[10]
 [20]
 [30]
 [40]]
[[100]
 [200]
 [300]
 [400]]
talonmies
  • 70,661
  • 34
  • 192
  • 269
2

It looks like loadmat returns recarray instead of dict. I checked with scipy 0.9.0. Equivalent of b['a'].keys() will be b['a'].dtype.names.

Examples:

In [12]: b['a'].shape
Out[13]: (1, 1)

In [14]: b['a'].dtype.names
Out[16]: ('test1', 'test3', 'test2')

In [17]: b['a']['test1']
Out[17]: array([[[[1]]]], dtype=object)
tkf
  • 2,990
  • 18
  • 32
  • This seems not to be working for me: `b['a'].dtype.names` returns nothing and `b['a']['test1']` returns `Traceback (most recent call last): File "", line 1, in ValueError: field named test1 not found.` – Framester Feb 13 '12 at 08:20