A simple question, but one I can't seem to be able to wrap my head around. I'm using the scipy.io library to save Python dictionaries as a Matlab structs. Now, the documentation of the scipy.io library shows us how to do this for a single Python Dictionary to a single Matlab Struct:
>>> a_dict = {'field1': 0.5, 'field2': 'a string'}
>>> sio.savemat('saved_struct.mat', {'a_dict': a_dict})
This sounds fair enough, and works:
However, I now want to do the same for multiple Python Dictionaries. I want them to be translated to a Matlab struct in which the column names are equal to the keys of all the dictionaries (which are obviously all the same keys names) and I want each row to represent the values for those keys for one of the Dictionaries. If I see this correctly, this is called a 1 x K struct with 10 fields, with K being the amount of rows (Python Dictionaries) I want to map. fields An example shown below:
Although I myself am totally unaware of correct Matlab terminology, a good soul in the comments told me this is supposed to be called a structure array. I have tried simply creating a numpy array of Python dictionaries, putting that in the a_dict key value pair of the code example above and saving that, but with no succes. Doing that results in a list of all different structs, instead of the one big struct with the rows representing the values for every individual struct.
As such, I am still in search of an appropriate solution for this problem. If you need any additional details, feel free to ask in the comments. Thanks for helping!
解决方案
Here's a solution:
In Python:
>>> a_dict = {'field1': 0.5, 'field2': 'a string'}
>>> b_dict = {'field1': 1, 'field2': 'another string'}
>>> sio.savemat('saved_struct.mat', {'dict_array':[a_dict,b_dict]})
In MATLAB:
s = load('saved_struct.mat');
struct_array = [s.dict_array{:}];
You will end up with a structure array in MATLAB as desired.
struct_array =
1×2 struct array with fields:
field1
field2