我好像有索引问题?我不知道如何解释这个错误。。。:/I我想这与我如何初始化u有关
我有一个3x3g矩阵,我用变量u(一个向量,x-y)创建的。我刚刚做了一个零矩阵,现在我还不太清楚如何编码它,有很多部分和规范涉及哈哈。x_j=(x_1(j)、x_2(j)、x_3(j))和y_j=(y_1(j)、y_2(j)、y_3(j))。x和y是nx3向量。αj是一个3x3矩阵。A矩阵是大小为3nx3n的块对角矩阵。我对W矩阵(大小为3nx3n,其中第(I,j)块是由alpha_I*G_[ij]*alpha_j给出的3x3矩阵)有问题。你知道吗
def G(u):
u1 = u[0]
u2 = u[1]
u3 = u[2]
g = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
return g
def W(x, y, k, alpha, A):
# initialization
n = x.shape[0] # the number of x vextors
result = np.zeros([3*n,3*n],complex)
u = np.matlib.zeros((n, 3)) # u = x - y
print(u)
num_in_blocks = n
# variables
a_i = alpha_j(alpha, A)
a_j = alpha_j(alpha, A)
for i in range(0, 2):
x1 = x[i] # each row of x
y1 = y[i] # each row of y
for j in range(0, n-1):
u[i][j] = x1[j] - y1[j] # each row of x minus each row of y
if i != j:
block_result = a_i * G((u[i][j]), k) * a_j
for k in range(num_in_blocks):
for l in range(num_in_blocks):
result[3*i + k, 3*j + l] = block_result[i, j]
return result
def alpha_j(a, A):
alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
n = A.shape[0]
rho = np.random.rand(n,1)
for i in range(0, n-1):
for j in range(0, n-1):
alph[i,j] = (rho[i] * a * A[i,j])
return alph
#------------------------------------------------------------------
# random case
def x(n):
return np.random.randint(100, size=(n, 3))
def y(n):
return np.random.randint(100, size=(n, 3))
# SYSTEM PARAMETERS
theta = 0 # can range from [0, 2pi)
chi = 10 + 1j
lam = 0.5 # microns (values between .4-.7)
k = (2 * np.pi)/lam # 1/microns
V_0 = (0.05)**3 # microns^3
K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])
alpha = (V_0 * 3 * chi)/(chi + 3)
A = np.matlib.identity(3)
#------------------------------------------------------------------
# TEST FUNCTIONS
w = W(x(3), y(3), k, alpha, A)
print(w)
我一直在u1=u[0]行中得到错误“对标量变量的索引无效”。你知道吗
np.matlib
生成一个np.matrix
,一个np.ndarray
的子类。它应该给人一种MATLAB的感觉,而且(几乎)总是产生一个2d数组。不鼓励在新代码中使用它。你知道吗使用[0]进行索引将拾取第一行,但返回2d矩阵。你知道吗
添加另一个[1]仍然索引第一个维度(现在的大小为1):
通常我们使用复合索引索引numpy数组:
如果我们改为
ndarray
:相关问题 更多 >
编程相关推荐