Numpy n对角矩阵广播分解

时间:2019-03-05 20:53:07

标签: python python-3.x numpy numpy-broadcasting

我想知道是否有更好的方法来利用python numpy数组广播来避免使用以下最小示例的两个内部for循环:

import numpy as np

# Parameters
n_t = 10
n_ddl = 3

# Typical dummy M n_ddl-diagonal matrix
x = np.arange(1,31)
x1 = np.arange(1,21)
x2 = np.arange(1,11)
M = np.diag(x) + np.diag(x1, 10) + np.diag(x1, -10) + np.diag(x2, 20) + np.diag(x2, -20)

# First loop remains
for i in range(0,n_t):
    M_i = np.zeros((n_ddl,n_ddl))
    # Optimize the following to get M_i
    for j in range(0,n_ddl,1):
        for k in range(0,n_ddl,1):
            M_i[j,k] = M[j*n_t+i,k*n_t+i]

任何改进语法或减少计算时间的建议将不胜感激。谢谢。

# Answer suggested using slicing
# First loop remains
for i in range(0,n_t):
    M_i_slicing = M[i:n_ddl*n_t:n_t,i:n_ddl*n_t:n_t]

1 个答案:

答案 0 :(得分:3)

以适当的步长大小简单切片并开始,因此删除了内部的两个循环-

for i in range(0,n_t):
    M_i = M[i::n_t,i::n_t]