将中矩阵的每个元素作为块重复到新矩阵中

2024-10-01 15:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在Matlab中,有一个命令repelem,其工作原理如下(参见https://www.mathworks.com/help/matlab/ref/repelem.html#buocbhj-2):

例如:创建一个矩阵,并将每个元素重复到一个3乘2的新矩阵块中。在

A = [1 2; 3 4]

B = repelem(A,3,2)

A = (2×2)
     1     2
     3     4

B = (6×4)
     1     1     2     2
     1     1     2     2
     1     1     2     2
     3     3     4     4
     3     3     4     4
     3     3     4     4

在Numpy中最好的方法是什么?在

^{pr2}$

Tags: https命令comref元素htmlwwwhelp
2条回答

因为您不需要改变任何元素,^{}是一个完美的解决方案。它允许我们以一种非常快速(且节省内存)的方式返回与所需重复次数匹配的视图:

def broadcast_tile(arr, h, w):
    x, y = a.shape
    m, n = x * h, y * w
    return np.broadcast_to(
        a.reshape(x, m//(h*x), y, n//(w*y)), (m//h, h, n//w, w)
    ).reshape(m, n)

broadcast_tile(a, 3, 2)

^{pr2}$

计时

In [425]: %timeit repelem(a, 200, 200)
770 µs ± 35.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [426]: %timeit broadcast_tile(a, 200, 200)
57.5 µs ± 2.27 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

您可以连锁指定^{cd2>}的^{}

repelem = lambda a, x, y: np.repeat(np.repeat(a, x, axis=0), y, axis=1)
# same as repelem  = lambda a, x, y: a.repeat(x, 0).repeat(y, 1)

打电话就行了

^{pr2}$

相关问题 更多 >

    热门问题