python读取mat数据是字典形式如何转化为矩阵_使用scipy.io savemat将多个Python字典转换为MATLAB结构数组...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值