不断获得 'only length-1 arrays can be converted to python scalars'

keep getting 'only length-1 arrays can be converted to python scalars'

我一直收到错误 only length-1 arrays can be converted to Python scalars。由于变量 'uc' 我收到错误,因为它是一个包含 214 个元素的数组。

错误状态:

  File "/home/lokesh/PycharmProjects/Cross_Range_Imaging/Cross_Range.py", line 68, in <module>
    dis = cmath.sqrt(Xc ** 2 + (Yc + yn[i] - uc) ** 2)
TypeError: only length-1 arrays can be converted to Python scalars

尝试过的代码:


import math
import cmath
import numpy as np

cj = cmath.sqrt(-1)
pi2 = 2 * cmath.pi
c = 3e8
fc = 200e6
Xc = 1e3
Yc = 0
Y0 = 100
L = 400
theta_c = cmath.atan(Yc / Xc)
L_min = max(Y0, L)
lamda = c / fc
Xcc = Xc / np.power(np.cos(theta_c),2)
duc = (Xcc * lamda) / (4 * Y0)
mc = 2 * math.ceil(L_min / duc)
uc = duc * np.arange(-mc / 2, mc/2)
k = pi2 / lamda

yn = [0, 70, 66.2500, -80]
fn = [1, 1, 1, 1]
ntarget = 4
s = np.zeros((1, mc))

for i in np.arange(ntarget):
    dis = cmath.sqrt(Xc ** 2 + (Yc + yn[i] - uc) ** 2)
    s = s + np.multiply(fn[i] * np.exp(-cj * 2 * k * dis), (abs(uc) <= L))

变量'dis'的预期结果值为1x214 double,变量's'的预期结果值为1x214 complex double

尝试dis = np.sqrt(Xc ** 2 + (Yc + yn[i] - uc) ** 2)

cmath.sqrt 对标量而不是数组进行运算。您必须使用像 numpy.sqrt() 这样的数组运算来获取数组中每个值的平方根。

注意:这将创建形状为 (214,)dis,它仍然适用于设置 s,但如果您希望 dis(1,214) ] 你可能想在我建议的代码末尾添加 .reshape(1, 214)