问题描述
使用 Python 3.8.1。和 Numpy 1.19.4
嘿伙计,我对 Python 有点陌生,所以请耐心等待。
我正在使用三个变量执行计算(模型/模拟),我需要逐步遍历每个变量的相应范围。当我从最终嵌套循环 (k) 中打印每次迭代时,每个范围的计算和循环似乎工作正常。但是,在循环后检查 v_ram 数组中存储的值时,这些值不正确,似乎反映了第三个 for 循环的最后一次迭代 (k=0:17),填充了数组的其余部分按零。
phi = np.linspace(0,(14/90)*pi,8,True) # 0 to 28 deg in 4 deg steps = 7 + 1 values
theta_step = 20 # theta step size = 20 deg
theta = np.linspace(0,(2*pi)-(theta_steP*(pi/180)),18,True) # 0 to (360-step) deg in 20 deg steps = 17 + 1
# number of simulations/length of resulting v_ram array
n_sim = len(v_sim_mag)*len(phi)*len(theta)
# Initialize the v_ram variable
v_ram = np.zeros((n_sim,3))
for i in range(len(v_sim_mag)):
for j in range(len(phi)):
for k in range(len(theta)):
v_ram[k] = [v_sim_mag[i] * math.sin(phi[j]) * math.cos(theta[k]),v_sim_mag[i] * math.sin(phi[j]) * math.sin(theta[k]),v_sim_mag[i] * math.cos(phi[j])]
print("v_ram:",v_ram[k],"v_sim_mag:",v_sim_mag[i],"phi:",phi[j],"theta:",theta[k],"i,j,k:",i,k)
print(v_ram)
输出:包括最后三行迭代的for循环打印为例,后跟数组v_ram的打印:
v_ram: [ 4.1858252 -7.25006191 15.74478445]
v_sim_mag: 17.83207132052525 phi: 0.4886921905584123 theta,i59,595,87.99
v_ram: [ 6.41305626 -5.38119314 15.74478445]
v_sim_mag: 17.83207132052525 phi: 0.4886921905584123 theta: 5,3876 k5,5,3656
v_ram: [ 7.8667781 -2.86327307 15.74478445]
v_sim_mag: 17.83207132052525 phi: 0.4886921905584123 theta: 5.94717194717194717
v_ram_array:
[[ 8.37165039 0. 15.74478445]
[ 7.8667781 2.86327307 15.74478445]
[ 6.41305626 5.38119314 15.74478445]
...
[ 0. 0. 0. ]
[ 0. 0. 0. ]
[ 0. 0. 0. ]]
非常感谢任何帮助,并随时烘烤我的代码并提供其他建议。
更新
# number of simulations/length of resulting v_ram array
n_sim = len(v_sim_mag)*len(phi)*len(theta)
# Initialize the v_ram variable
v_ram = np.zeros((len(v_sim_mag),len(phi),len(theta),6))
for i in range(len(v_sim_mag)):
for j in range(len(phi)):
for k in range(len(theta)):
v_ram[i,k] = [v_sim_mag[i] * math.sin(phi[j]) * math.cos(theta[k]),v_sim_mag[i] * math.cos(phi[j]),k]
解决方法
v_ram.shape
是 (2160,3)
,但您只分配给 v_ram[k]
,最多为 17。也许您的意思更像是:
v_ram = np.zeros((n_sim,3))
v_ram_index = 0
循环核心如下:
v_ram[v_ram_index] = [
v_sim_mag[i] * math.sin(phi[j]) * math.cos(theta[k]),v_sim_mag[i] * math.sin(phi[j]) * math.sin(theta[k]),v_sim_mag[i] * math.cos(phi[j])]
v_ram_index += 1