[英]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 : 我想知道是否有更好的方法利用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]
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.