根据 What is the equivalent of MATLAB's repmat in NumPy ,我尝试使用 python 从 3x3 数组构建 3x3x5 数组。
在 Matlab 中,这符合我的预期。
a = [1,1,1;1,2,1;1,1,1];
a_= repmat(a,[1,1,5]);
大小(a_) = 3 3 5
但是对于 numpy.tile
b = numpy.array([[1,1,1],[1,2,1],[1,1,1]])
b_ = numpy.tile(b, [1,1,5])
b_.shape = (1, 3, 15)
如果我想生成与在 Matlab 中相同的数组,等效项是什么?
编辑 1
我希望得到的输出是
b_(:,:,1) =
1 1 1
1 2 1
1 1 1
b_(:,:,2) =
1 1 1
1 2 1
1 1 1
b_(:,:,3) =
1 1 1
1 2 1
1 1 1
b_(:,:,4) =
1 1 1
1 2 1
1 1 1
b_(:,:,5) =
1 1 1
1 2 1
1 1 1
但是@farenorth 和 numpy.dstack
给出的是
[[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]
[[1 1 1 1 1]
[2 2 2 2 2]
[1 1 1 1 1]]
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]]
最佳答案
NumPy 函数通常不是 matlab 函数的“直接”替代品。通常,“等效”函数的使用方式存在细微差别。适应确实需要时间,但我发现这种转变非常值得。
在这种情况下,np.tile
文档指出当您尝试将数组平铺到比定义的更高维度时会发生什么,
numpy.tile(A, reps)
Construct an array by repeating A the number of times given by reps.
If reps has length d, the result will have dimension of max(d, A.ndim).
If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.
在这种情况下,您的数组被转换为 [1, 3, 3]
的形状,然后被平铺。因此,要获得您想要的行为,请确保将一个新的单例维度附加到您想要的数组中,
>>> b_ = numpy.tile(b[..., None], [1, 1, 5])
>>> print(b_.shape)
(3, 3, 5)
请注意,我在此处使用了 None
(即 np.newaxis
)和省略号来指定数组末尾的新维度。您可以找到有关这些功能的更多信息 here .
受 OP 评论启发的另一种选择是:
b_ = np.dstack((b, ) * 5)
在这种情况下,我使用元组乘法来“repmat”数组,然后由 np.dstack
构造.
正如@hpaulj 指出的那样,Matlab 和 NumPy 显示矩阵的方式不同。要复制 Matlab 输出,您可以执行以下操作:
>>> for idx in xrange(b_.shape[2]):
... print 'b_[:, :, {}] = \n{}\n'.format(idx, str(b_[:, :, idx]))
...
b_[:, :, 0] =
[[1 1 1]
[1 2 1]
[1 1 1]]
b_[:, :, 1] =
[[1 1 1]
[1 2 1]
[1 1 1]]
b_[:, :, 2] =
[[1 1 1]
[1 2 1]
[1 1 1]]
b_[:, :, 3] =
[[1 1 1]
[1 2 1]
[1 1 1]]
b_[:, :, 4] =
[[1 1 1]
[1 2 1]
[1 1 1]]
祝你好运!
关于python - numpy.tile 不能作为 Matlab repmat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32238227/