簡體   English   中英

嵌套的FOR循環索引問題-Python

[英]Nested FOR loop indexing issue - Python

我在嵌套的for循環中遇到索引問題。 Python吐出了一個索引錯誤,告訴我我的索引超出范圍。

以下是我的代碼和后續錯誤:

from math import *
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
import os

croot = 1
ctip = 1
span = 1
thetaroot = 0
thetatip = 0
a0root = 0.11
a0tip = 0.11
alpha = 0
alpha0root = -2.5
alpha0tip = -2.5
thetaroot = thetaroot * arctan(1.) / 45.
thetatip = thetatip * arctan(1.) / 45.
alpha = alpha * arctan(1.) / 45.
alpha0root = alpha0root * arctan(1.) / 45.
alpha0tip = alpha0tip * arctan(1.) / 45.
n = 10
theta = np.empty(n, dtype = object)
y = np.empty(n, dtype = object)
c = np.empty(n, dtype = object)
cl = np.empty(n, dtype = object)
alp = np.empty(n, dtype = object)
a = np.empty(n, dtype = object)
rhs = np.empty(n, dtype = object)
b = np.empty(n, dtype = object)
a = np.empty(n, dtype = object)
rhs = rhs[:,None]
b = b[:,None]
a = a[:,None]
#
# Define properties at n span stations
#
pi = 4. * arctan(1.)
for i in range(0,n):
    theta[i] = i * pi / (2. * n)
    y[i] = span * 0.5 * cos(theta[i])
    c[i] = croot + (ctip - croot) * y[i] * 2. / span
    alp[i] = alpha + thetaroot - (alpha0root + (alpha0tip - alpha0root + thetaroot - thetatip) * y[i] * 2. / span)
    a[i] = a0root + (a0tip - a0root) * y[i] * 2. / span

pi = 4. * arctan(1.)
# Set up 2n x 2n system of equations for A1, A3 , ... A2n-1
for j in range(0,n):
    mu = c[j] * a[j] / (4. * span); print('mu=',mu)
    rhs[j,0] = alp[j] * sin(theta[j]) * c[j] * a[j] / (4 * span)
    for i in range(0,n):
        l = 2 * i - 1
        b[j,i] = sin(l * theta[j]) * (mu * l + sin(theta[j]))

然后,我收到錯誤消息:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-70-b5bd95e69bb5> in <module>()
     45     for i in range(0,n):
     46         l = 2 * i - 1
---> 47         b[j,i] = sin(l * theta[j]) * (mu * l + sin(theta[j]))
     48 
     49 

IndexError: index 1 is out of bounds for axis 1 with size 1

如何有效調出兩個索引? 在MATLAB中,b(j,i)是常規語法。

任何幫助表示贊賞,謝謝!

調用n=10 b = np.empty(n, dtype = object)構成一維數組,但您正在對其進行索引( b[j,i] ),就好像它是二維數組一樣。

要初始化10 x 10數組,您可以調用b = np.empty([n, n], dtype = object)

編輯:我沒有注意到此分配: b = b[:,None]創建此:

>>> [[None]
 [None]
 [None]
 [None]
 [None]
 [None]
 [None]
 [None]
 [None]
 [None]]

這是一個二維數組,但是嘗試索引內部數組的第一個元素(僅包含None)會導致您的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM