0
Hello, I would like to know how to write a tridiagonal matrix Nxn. I have three vectors that will be updated in a loop.
I’m working with something semlhnante to this:
Note: I would just like to know about zeroes and what Python parameters I could use to adjust this. Well, I have two codes here, the first I wrote in Fortran and it’s working fine. The second is what I tried to write in Python.
Fortran:
do i=2,n-1
do j=2,n-1
if (i.eq.j) then
D(i,j+1)=-u_med(i+1)/(delta_r(i)*delta_r(i+1))
t1 =u_med(i+1)/(delta_r(i)*delta_r(i))
t2 = u_med(i)/(delta_r(i)*delta_r(i))
D(i,j)= t1 + t2 + V(i)
D(i+1,j)=-u_med(i+1)/(delta_r(i)*delta_r(i+1))
end if
end do
end do
Python:
for i in range(2,n):
for j in range(2,n):
if i == j:
D[i][j+1] = - u_med[i+1]/(delta_r[i]*delta_r[i+1])
t1 = u_med[i+1]/(delta_r[i]*delta_r[i])
t2 = u_med[i]/(delta_r[i]*delta_r[i])
D[i][j]= t1 + t2 + V[i]
D[i+1][j]= - u_med[i+1]/(delta_r[i]*delta_r[i+1])
t1 = u_med[2]/(delta_r[1]*delta_r[1])
t2 = 0
D[1][1]= t1 + t2 + V[1]
D[1][2]= - u_med[2]/(delta_r[1]*delta_r[2])
D[2,1]= - u_med[2]/(delta_r[2]*delta_r[1])
t1 = 0
t2 = u_med[n]/(delta_r[n]*delta_r[n])
D[n][n]= t1 + t2 + V[n]
That makes the mistake:
D[i][j+1] = - u_med[i+1]/(delta_r[i]*delta_r[i+1]) Valueerror: Setting an array element with a Sequence.
Definitions of u_med
, delta_r
, r
, n
and D
in Python:
u_med = np.zeros((n,2))
for i in range(2,n):
tta1 = r[i]*u[i]
tta2 = r[i-1]*u[i-1]
u_med[i] = 0.5*(tta1 + tta2)/(r[i] - r[i-1])
u_med[1] = u_med[2]
delta_r = np.zeros((n-1,2))
for i in range(2,n-1):
ft1 = r[i+1]*r[i+1]
ft2 = r[i-1]*r[i-1]
ft3 = 2*r[i]*(r[i+1] - r[i-1])
delta_r[i] = math.sqrt(0.125*abs(ft1 - ft2 + ft3))
ri=0
n1 = 51
r1 = ri
r2 = 250
hr1 = (r2-r1)/(n1-1)
r = np.zeros((n1,1))
for i in range(n1):
r[i] = r1 + i*hr1
u = np.zeros((n+1,1))
for i in range(1,n+1):
i = 1
D = npm.zeros((n,n))
I suspect the mistake is in:
D = npm.zeros((n,n))
But how could I rewrite it?
Probably the problem is happening due to
u_med
anddelta_r
be bi-dimensional and you try to assign a sub-array (vector) of these variables to a position in the variableD
with a Shape incompatible. This works in Fortran, but should be done differently in Python. See: Assigning values to Indexed arrays– Gomiero
In fact
u_med
anddelta_r
are one-dimensional...D
is that it is two-dimensional. Somehow these are defined as two-dimensional?– oklucas
You defined
u_med
asnp.zeros((n,2))
(n rows and 2 columns) anddelta_r
asnp.zeros((n-1,2))
(n-1 rows and 2 columns), therefore, they are two-dimensional– Gomiero