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

Asked

Viewed 361 times

0

i am beginner in python and I am in doubt in matrix mounting. In 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

Which 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 matrix elements):

 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 large number, how would I do? I tried using the:

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

But in this case, it gives error message warning that i and j have not been specified to be able to calculate k, L1,L2, L3 and L4. I don’t know yet how to use the codes for matrix. (The value of n will always be changed).

1 answer

1


Maybe your problem is with range.

If I’m gonna use n=3, range(2,n-1) returns [] and he doesn’t pass the loop, leaving A without any alteration and also does not create i,j, and other variables created within the 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 have simplified the numbers assigned to A. See that in this case, i and j will have their different values in each iteration for n>3.

I don’t know if that’s what you want, but that’s what I got from your code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.