我正在尝试计算以下内容:
def E_inc_j(tilde_k, x, vecinc):
n = x.shape[0]
e = np.zeros((n, 3))
for i in range(n):
for j in range(3):
e[i] = np.exp(1j * tilde_k * x[i]) * vecinc
return e
def x(n):
return np.random.randint(100, size=(n, 3))
lam = 0.5
k = (2 * np.pi)/lam
theta = 0
K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])
vecinc = np.array([[1], [0], [0]])
E_inc_j_test = E_inc_j(K, x(5), vecinc)
print(E_inc_j_test)
在行e[i] = np.exp(1j * tilde_k * x[i]) * vecinc
上出现错误“无法将输入数组从形状(3,3)广播到形状(3)”。
*****最终结果应该是3N x 1向量。 *****
答案 0 :(得分:0)
根本不需要for循环:
import numpy as np
k = 10.
theta = 0.3
K = k * np.array([0, np.sin(theta), np.cos(theta)])
x = np.random.randint(100, size=(7, 3))
vecinc = np.array([1, 0, 0])
e = np.exp(1j * K * x) * vecinc
# array([[ 1.+0.j, 0.+0.j, 0.-0.j],
# [ 1.+0.j, 0.-0.j, 0.-0.j],
# [ 1.+0.j, 0.+0.j, 0.+0.j],
# [ 1.+0.j, 0.-0.j, -0.+0.j],
# [ 1.+0.j, 0.+0.j, -0.+0.j],
# [ 1.+0.j, 0.-0.j, 0.+0.j],
# [ 1.+0.j, -0.+0.j, -0.+0.j]])