简体   繁体   中英

Numpy n-diagonal matrix broadcasting decomposition

I would like to know if there is a better way of taking advantage of python numpy array broadcasting to avoid the use of the two inner for loops of the following minimal example :

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]

Any suggestions to improve syntax or reduce computation time would be greatly appreciated. Thanks.

# 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]

Simply slice with appropriate step-sizes and starts and hence remove the inner two loops -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM