How to mount an array in python with undefined value of i and j

0

I'm a beginner in python and I'm doubtful about array assembly. In the case, I did the following:

import numpy as np
n=3
A = np.zeros((n*n,n*n))
j= 2
i = 2
k = i+n*(j-1)
a = -4
L1 = i-1+n*(j-1)
a1 = 1
L2 = i+1+n*(j-1)
a2 = 1
L3 = k-n
a3 = 1
L4 = k+n
a4 = 1
A [k-1, k-1] = a
A [k-1, L1-1] = a1
A [k-1, L2-1] = a2
A [k-1, L3-1] = a3
A [k-1, L4-1] = a4

That results in:

[[0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0. 0.  0.  0.  0.  0.   0.  0.]
 [ 0.  0.  0. 0.  0.  0.  0.   0.  0.]
 [ 0.  1.  0.  1. -4.  1.  0.  1.  0.]
 [ 0.  0.  0.  0.  0. 0.   0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.]]

But the value of i and j are (are elements of the matrix):

 i = 2, n-1
 j = 2, n-1

In the case of n = 3, it was easy to assume that i and j would be 2, but in the case of n with a large number, how would I do it? I tried using the:

for j in range (2, n-1):
        for i in range (2, n-1):

But in this case, it gives an error message that i and j have not been specified to calculate k, L1, L2, L3 and L4. I'm not sure yet how to use the array codes. (The value of n will always change.)

    
asked by anonymous 08.11.2017 / 03:50

1 answer

1

Maybe your problem is with range .

If I use n=3 , range(2,n-1) returns [] and it does not pass in the loop, leaving A without any change and also does not create i , j , and other variables created within loop.

Using the code below it works normally.

n=3
A = np.zeros((n*n,n*n))
for j in range (2, n):
    for i in range (2, n):
       k = i+n*(j-1)
       L1 = i-1+n*(j-1)
       L2 = i+1+n*(j-1)
       L3 = k-n
       L4 = k+n
       a=1
       A [k-1, k-1] = a-5
       A [k-1, L1-1] = a
       A [k-1, L2-1] = a
       A [k-1, L3-1] = a
       A [k-1, L4-1] = a

Note that I simplified the numbers assigned to A . Note that in this case, i and j will have their different values in each iteration for n> 3.

I do not know if this is what you want, but that's what I understood from your code.

    
09.11.2017 / 18:19