Home > OS >  how i can calculate the adjacent and opposite of this matrix?
how i can calculate the adjacent and opposite of this matrix?

Time:12-16

I have this matrix

Matrix = [[0., 15., 19., 18., 17.],
     [15., 0., 14., 12., 23.],
     [19., 14.,  0., 14., 21.],
     [18., 12., 14., 0., 14.],
     [17., 23., 21., 14.,  0.]]

and I cut it to this by this code

c = [item[:index 1] for index, item in enumerate(Matrix[1:])]
c

It shows that

[array([15.]),
 array([19., 14.]),
 array([18., 12., 14.]),
 array([17., 23., 21., 14.])]

and I want to calculate the adjacent and the opposite of this matrix example: 15 19 18 17 and 19 14 12 23 and 18 12 14 21 and 17 23 21 14 How can I do that?

I tried this to append all data and work on it but it shows nothing

arr=[]
for item,data in enumerate(c):
          for item2,data2 in enumerate(data):
                    arr.append(data2)
                    print(item,item2,data2)

print(arr)

**And I try the code below and it prints the diagonal **

for item,data in enumerate(c):
          print(data[item:item 1])

and I try this and it shows

for item,data in enumerate(c):
    print(item, data[0:1], data[1:2],data[2:3],data[3:4])
0 [15.] [] [] []
1 [19.] [14.] [] []
2 [18.] [12.] [14.] []
3 [17.] [23.] [21.] [14.]

So I realized that I can iterate just on columns not on row is there any method to solve it? This is an example that I want to implement to better understand, here I want to calculate the summation of these vectors this example that i want to implement

CodePudding user response:

It looks like you are trying to calculate sum of rows of 'symmetrised' submatrix. I'll explain step by step.

At first, create a copy of submatrix:

>>> arr = Matrix[1:,:-1].copy()
>>> arr
array([[15.,  0., 14., 12.],
       [19., 14.,  0., 14.],
       [18., 12., 14.,  0.],
       [17., 23., 21., 14.]])

Then find a way to fill right upper triangle with values of left lower triangle. You could find both indices of left lower triangle and indices right upper triangle and use advanced indexing to modify values of arr:

>>> idx = np.triu_indices(len(arr), 1) #indices of right upper triangle
>>> arr[idx] = arr.T[idx] #use advanced indexing to modify values
>>> arr
array([[15., 19., 18., 17.],
       [19., 14., 12., 23.],
       [18., 12., 14., 21.],
       [17., 23., 21., 14.]])

For better understanding of indexing you could also try to take a look at indices like you did in your double for looping:

>>> np.transpose(idx)
array([[0, 1],
       [0, 2],
       [0, 3],
       [1, 2],
       [1, 3],
       [2, 3]])

Finally, calculate sums of rows:

>>> arr.sum(axis=0)
array([69., 68., 65., 75.]) #15 19 18 17, 19 14 12 23, 18 12 14 21 and 17 23 21 14 
  • Related