使用scipy.io savemat将多个Python字典转换为MATLAB结构数组 [英] Convert multiple Python dictionaries to MATLAB structure array with scipy.io savemat

查看:453
本文介绍了使用scipy.io savemat将多个Python字典转换为MATLAB结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,但是我似乎无法绕开我的头.我正在使用scipy.io库将Python词典另存为Matlab结构.现在,文档 scipy.io库的示例向我们展示了如何将单个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:

但是,我现在想对多个Python字典执行相同的操作.我希望将它们转换为Matlab结构,其中列名等于所有字典的键(显然都是相同的键名),并且我希望每一行代表其中一个键的那些键的值字典.如果我正确地看到了这一点,则将其称为具有10个字段的1 x K结构,其中K是我要映射的行数(Python字典).字段下面显示了一个示例:

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:

尽管我本人并不完全了解正确的Matlab术语,但评论中的好人告诉我这应该称为结构数组.我试过简单地创建一个python字典的numpy数组,将其放入上面的代码示例的a_dict键值对中并保存,但是没有成功.这样做会得到所有不同结构的列表,而不是一个大结构,其中的行代表每个单独结构的值.

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!

推荐答案

这是一个解决方案:

在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]})

在MATLAB中:

s = load('saved_struct.mat');
struct_array = [s.dict_array{:}];

您将根据需要在MATLAB中获得一个结构数组.

You will end up with a structure array in MATLAB as desired.

struct_array = 

  1×2 struct array with fields:

    field1
    field2

这篇关于使用scipy.io savemat将多个Python字典转换为MATLAB结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆