在python中创建Matlab单元数组 [英] creating Matlab cell arrays in python

查看:152
本文介绍了在python中创建Matlab单元数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中创建Matlab单元格数组并将其另存为.mat文件,但是当所有单元格都包含2个值时会遇到问题:

I'm trying to create a Matlab cell array in python and save it as a .mat file, but am running into problems when all the cells contain 2 values:

import scipy.io as sio

twoValues = {'a': array([[array([[2, 2]]), array([[3, 3]])]])}
sio.savemat('test.mat',twoValues)

在Matlab中:

load('test.mat')
>>> a

a(:,:,1,1) =

           2           3


a(:,:,1,2) =

           2           3


>>> class(a)

ans =

int32

返回python:

threeValues = {'a': array([[array([[2, 2, 2]]), array([[3, 3]])]])}
sio.savemat('test.mat',threeValues)

在Matlab中:

>>> a

a = 

    [3x1 int32]    [2x1 int32]


>>> class(a)

ans =

cell

这是什么原因?

推荐答案

执行此操作时:

a = np.array([[np.array([[2, 2]]), np.array([[3, 3]])]])

np.array的最终调用实际上将内部的两个连接在一起,因此您在末尾得到一个数组:

the final call to np.array actually concatenates the inner two, so you get one array at the end:

>>> a
array([[[[2, 2]],

        [[3, 3]]]])

>>> a.shape
(1, 2, 1, 2)

但是要模仿单元格数组,您基本上希望拥有数组的数组.您可以通过设置dtype=object来实现此目的,但是必须创建数组并分别设置元素,以避免自动合并.

But to mimic a cell array you want to basically have an array of arrays. You can acheive this by setting dtype=object, but you must create the array and set the elements separately to avoid the automatic merging.

three = array([[array([[2, 2, 2]]), array([[3, 3]])]])
two = np.empty(three.shape, dtype=object)
two[0,0,0] = np.array([[2,2]])
two[0,1,0] = np.array([[3,3]])

然后:

sio.savemat('two.mat', {'two': two})

查看它们的外观:

>>> two
array([[[array([[2, 2]])],
        [array([[3, 3]])]]], dtype=object)

>>> two.shape
(1, 2, 1)

请注意,由于您有太多嵌套的括号,我可能对您想要的形状感到困惑,因此您可能需要重塑其中的一些形状,但是无论如何都应保留这种想法.

Note that I may have gotten confused about your desired shape, since you have so many nested brackets, so you might have to reshape some of this, but the idea should hold regardless.

这篇关于在python中创建Matlab单元数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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