0

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?

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.