【问题标题】:matlab for loop to python loopmatlab for循环到python循环
【发布时间】:2021-10-06 17:39:32
【问题描述】:

我正在尝试更改此 Matlab for 循环:

n =100;
u_lsg = zeros (n ,n) ; 
for i =1:1: n
    for j =1:1: n
        u_lsg(i , j) =( i*h)*(j*h )*(1 -( i*h ))*(1 -( j*h ));
    end
end

进入python循环。

到目前为止我得到了什么:

n =100
u_lsg = np.zeros((n ,n))
for i in range (1,n+1,1):
    for j in range (1,n+1,1):
        u_lsg[i,j]= (i*h)*(j*h)*(1-(i*h))*(1-(j*h))

但这给了IndexError: index 100 is out of bounds for axis 1 with size 100

我做错了什么?据我了解,python 中没有end 命令,但是如何结束循环呢?

【问题讨论】:

    标签: python matlab for-loop


    【解决方案1】:

    Matlab 是 1-indexed(数组索引从 1 开始),Python(和 NumPy)是 0-indexed(数组索引从 0 开始),所以只需相应地更改范围:

    n = 100
    u_lsg = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            u_lsg[i, j] = (i*h)*(j*h)*(1-(i*h))*(1-(j*h))
    

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      相关资源
      最近更新 更多