ggraann
ggraann

Reputation: 35

matlab for loop to python loop

I'm trying to change this Matlab for loop:

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

into a python loop.

What I've got so far:

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))

But this gives IndexError: index 100 is out of bounds for axis 1 with size 100.

What did I do wrong? And from what I understand there is no end command in python, but then how does one end the loop?

Upvotes: 0

Views: 110

Answers (1)

Djaouad
Djaouad

Reputation: 22794

Matlab is 1-indexed (array indices start at 1), Python (and NumPy) is 0-indexed (array indices start at 0), so just change the ranges accordingly:

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))

Upvotes: 1

Related Questions