首页 > 编程知识 正文

python生成n阶单位矩阵,python创建单位矩阵

时间:2023-05-03 20:05:33 阅读:276309 作者:3450

一种方法是初始化4D的输出数组,然后从A向其赋值。这样的任务会传播价值观,而这正是我们在NumPy中获得效率的地方。在

因此,解决方案应该是这样的-# Get shape of A

m,n = A.shape

# Initialize output array as 4D

out = np.zeros((m,N,n,N))

# Get range array for indexing into the second and fourth axes

r = np.arange(N)

# Index into the second and fourth axes and selecting all elements along

# the rest to assign values from A. The values are broadcasted.

out[:,r,:,r] = A

# Finally reshape back to 2D

out.shape = (m*N,n*N)

作为函数-

^{pr2}$

要模拟np.kron(np.eye(N), A),只需沿着第一个和第二个轴交换操作,对于第三个和第四个轴-def kron_N_A(A, N): # Simulates np.kron(np.eye(N), A)

m,n = A.shape

out = np.zeros((N,m,N,n),dtype=A.dtype)

r = np.arange(N)

out[r,:,r,:] = A

out.shape = (m*N,n*N)

return out

时间安排-In [174]: N = 100

...: A = np.random.rand(100,100)

...:

In [175]: np.allclose(np.kron(A, np.eye(N)), kron_A_N(A,N))

Out[175]: True

In [176]: %timeit np.kron(A, np.eye(N))

1 loops, best of 3: 458 ms per loop

In [177]: %timeit kron_A_N(A, N)

10 loops, best of 3: 58.4 ms per loop

In [178]: 458/58.4

Out[178]: 7.842465753424658

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。