我试图在 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/