I am a beginner in python and trying to write a code to determine the admittance matrix. my admittance list is defined as Y_ges
Y_ges = [ 9.89583333-40.47448077j 27.9209622 -10.73883162j
27.9209622 -10.73883162j 27.9209622 -10.73883162j
27.9209622 -10.73883162j]
At the beginning i created a zero matrix and determined its size.
a=np.zeros((len(net.bus),len(net.bus)),dtype=complex)
then i created a function to fill the matrix row by row
def fillmatrix(n):
for i in range(len(n)):
#print(i)
if i == 0 :
zerolist=[0]*len(net.bus)
print("we are in if loop",i)
zerolist[i]=Y_ges[i]
zerolist[i+1]=-Y_ges[i]
a[i]=zerolist
#print(zerolist)
#print(a)
else:
print("we are in else loop",i)
zerolist=[0]*len(net.bus)
zerolist[i-1]=-Y_ges[i-1]
zerolist[i]=Y_ges[i-1]+Y_ges[i+1]
zerolist[i+1]=-Y_ges[i+1]
a[i]=zerolist
i+=1
print(a)
print("i =",i)
#print(zerolist)
fillmatrix(Y_ges)
i expect this matrix
[[ 9.89583333-40.47448077j -9.89583333+40.47448077j
0. +0.j 0. +0.j
0. +0.j 0. +0.j ]
[ -9.89583333+40.47448077j 37.81679553-51.21331239j
-27.9209622 +10.73883162j 0. +0.j
0. +0.j 0. +0.j ]
[ 0. +0.j -27.9209622 +10.73883162j
55.8419244 -21.47766323j -27.9209622 +10.73883162j
0. +0.j 0. +0.j ]
[ 0. +0.j 0. +0.j
-27.9209622 +10.73883162j 55.8419244 -21.47766323j
-27.9209622 +10.73883162j 0. +0.j ]
[ 0. +0.j 0. +0.j
0. +0.j -27.9209622 +10.73883162j
55.8419244 -21.47766323j -27.9209622 +10.73883162j]
[ 0. +0.j 0. +0.j
0. +0.j 0. +0.j
-27.9209622 +10.73883162j 27.9209622 +10.73883162j]]
but i get this matrix
[[ 9.89583333-40.47448077j -9.89583333+40.47448077j
0. +0.j 0. +0.j
0. +0.j 0. +0.j ]
[ -9.89583333+40.47448077j 37.81679553-51.21331239j
-27.9209622 +10.73883162j 0. +0.j
0. +0.j 0. +0.j ]
[ 0. +0.j -27.9209622 +10.73883162j
55.8419244 -21.47766323j -27.9209622 +10.73883162j
0. +0.j 0. +0.j ]
[ 0. +0.j 0. +0.j
-27.9209622 +10.73883162j 55.8419244 -21.47766323j
-27.9209622 +10.73883162j 0. +0.j ]
[ 0. +0.j 0. +0.j
0. +0.j 0. +0.j
0. +0.j 0. +0.j ]
[ 0. +0.j 0. +0.j
0. +0.j 0. +0.j
0. +0.j 0. +0.j ]]
and this error message:
File "/Users/pythonuser/Desktop/Probe code ", line 230, in <module>
fillmatrix(Y_ges)
File "/Users/pythonuser/Desktop/Probe code ", line 220, in fillmatrix
zerolist[i]=Y_ges[i-1]+Y_ges[i+1]
IndexError: index 5 is out of bounds for axis 0 with size 5
any idea ?
Numpy arrays are zero indexed. It starts at index zero and ends with the last element at index len-1. You shouldn't modify i in the loop.
I have read your code and understood that you want a somewhat diagonal matrix, so here goes the code:
def fillmatrix(n):
zeros = np.zeros((len(n)+1, len(n)+3), dtype=n.dtype)
p = np.pad(n, 1) # padding simplifies the logic, no ifs
for i in range(len(n)+1):
zeros[i, i:i+3] = [-p[i], p[i]+p[i+1], -p[i+1]]
return zeros[:, 1:-1]