python - 在 python 中创建 Matlab 元胞数组

标签 python matlab scipy

我试图在 python 中创建一个 Matlab 元胞数组并将其保存为 .mat 文件,但是当所有元胞都包含 2 个值时我遇到了问题:

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 的最后一次调用实际上连接了内部的两个数组,所以最后得到一个数组:

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

        [[3, 3]]]])

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

但要模仿 cell array你基本上想要一个数组数组。您可以通过设置 dtype=object 来实现这一点,但是您必须创建数组并分别设置元素以避免自动合并。

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)

请注意,我可能对您想要的形状感到困惑,因为您有太多嵌套的括号,所以您可能需要 reshape 其中的一些形状,但无论如何这个想法都应该成立。

关于python - 在 python 中创建 Matlab 元胞数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19797822/

相关文章:

python - MongoDB 需要安装才能与 pymongo 一起使用吗?

python - Pandas DataFrame 分组

c++ - MATLAB + Mex + OpenCV : Links and compiles correctly but can't find library at run time

matlab - 紧凑的 MATLAB 矩阵索引符号

python - 获得包含折线图的两个图像的相似性度量的好方法是什么?

python - 填补 numpy 数组中的空白

python - Scipy - 非线性方程组的所有解

python - 如何用箭头连接 3D 散点图中的两个点?

python - 如何将文件从Azure blob复制到Linux中的某些路径

matlab - 高斯朴素贝叶斯分类