Saving matlab file using python

I have a complex data structure

data = {} temp = {} data['bigdata'] = temp; 

After that, I copy the "key" and "data" values ​​from some other data structure to temp, for example,

 for key in backup.keys(): temp[key] = [] 

and

 for key in backup.keys(): for val in backup[key]: temp[key].append(val); 

After that if i do

 sio.savemat(outputMATfile,data,oned_as ='column') 

he gives me an error saying

 TTypeError: data type not understood 

Is it not possible to store such a complex dictionary in a matlab file using python?

+6
source share
1 answer

edit: the answer (and the question is somewhat) has changed significantly to be more general. It would be useful for the asker to tell us which objects have values ​​in backup .

Scipy.io.savemat can apparently take a dictionary of dictionaries of arrays, so this structure

 from numpy import array import scipy.io data = { 'bigdata' : { 'a' : array([1, 2, 3]), 'b' : array([1, 2, 3]), 'c' : array([1, 2, 3]), } } scipy.io.savemat('test.mat', data) 

loaded into matlab as

 >> load test.mat >> bigdata bigdata = a: [3x1 int64] c: [3x1 int64] b: [3x1 int64] 

I assume that these dictionaries can be nested to the limit of python recursion, since the implementation is recursive. I checked 6 levels of dictionary breeding. Edit: now you are asking about such a structure:

 data = { 'key1' : ['a' : apple, 'b' : banana], 'key2' : ['c' : crabapple, 'd' : dragonfruit], ... } 

and you did not indicate what an apple, a banana, etc. It depends on what data from these Python objects you need in Matlab objects. I checked several classes, such as str (converted to a char array), set (failed to convert to an array) and a list (an array, if it is homogeneous, an array of characters, if some lines, some numbers). The code looks pretty duck, so if these objects have a common interface for storing data, it must go through; I present an excerpt from the most relevant bit for the matlab5 version:

 def to_writeable(source) if isinstance(source, np.ndarray): return source if source is None: return None # Objects that have dicts if hasattr(source, '__dict__'): source = dict((key, value) for key, value in source.__dict__.items() if not key.startswith('_')) # Mappings or object dicts if hasattr(source, 'keys'): dtype = [] values = [] for field, value in source.items(): if (isinstance(field, basestring) and not field[0] in '_0123456789'): dtype.append((field,object)) values.append(value) if dtype: return np.array( [tuple(values)] ,dtype) else: return None # Next try and convert to an array narr = np.asanyarray(source) if narr.dtype.type in (np.object, np.object_) and \ narr.shape == () and narr == source: # No interesting conversion possible return None return narr 
+6
source

Source: https://habr.com/ru/post/898844/


All Articles