python 数据保存 matlab,使用python存储matlab文件

这篇博客探讨了如何将包含嵌套字典和数组的Python数据结构转换并保存到MATLAB文件中。通过使用scipy.io.savemat函数,可以成功地保存字典和数组。内容涉及了数据类型转换,包括字符串、集合和列表,并强调了转换过程中的兼容性和限制。博主还进行了六层嵌套字典的测试,表明该方法在一定范围内是可行的。
摘要由CSDN通过智能技术生成

编辑:答案(和问题有点)已经发生了显著的变化,变得更加普遍。如果询问者告诉我们backup中的值是什么类型的对象,这还是很有用的。在

在scipy.io.savemat显然可以取字典的数组,所以这个结构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)

加载到matlab as中

^{pr2}$

我认为这些字典可以嵌套到python的递归限制,因为实现是递归的。我测试了6个层次的嵌套字典。

编辑:现在你要问的是这样一个结构:data = {

'key1' : ['a' : apple, 'b' : banana],

'key2' : ['c' : crabapple, 'd' : dragonfruit],

...

}

你还没有具体说明什么是苹果、香蕉等。这取决于您希望在Matlab对象中从这些Python对象中获取什么数据。我测试了一些类,比如str(转换为char数组)、set(无法转换为array)和list(如果是同构的,则是array,如果是字符串,则是一些数字)等。代码看起来很像duck-type-ish,所以如果这些对象有一个公共的数据保存接口,它应该可以通过;我在这里为matlab5版本提供一个most relevant bit的摘录: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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值