Search code examples
pythonnew-operator

for loop in a matrix


im trying to apply a function $y=(x_i-x_j)$ for every combination of i and j. And j,i={1,2,...,5} and x={10,-15,13,20,-4}. For example for i=1 and j=1 we have that y=x_1-x_1=0. Now for i=1 and j=2 we have that y=x_2-x_1=25

In my head i was thinking of a matrix like this enter image description here

I have tried a for loop but i dont know how to make it like a matrix

y=[]
for k in range(0,4) 
         for j in range (0,4)
              y.append(x[k]-x[j])

But is not working as i want it. Can you guys give me a hand. Thank you


Solution

  • This works:

    import pprint
    
    x_in = [10, -15, 13, 20, -4]
    
    matrix = [[[0]  for i in range(len(x_in))] for i in range(len(x_in))]
    
    for i, x1 in enumerate(x_in):
        for j, x2 in enumerate(x_in):
            matrix[j][i] = x1 - x2
    
    pprint.pprint(matrix)
    

    Output:

    [[0, -25, 3, 10, -14],
     [25, 0, 28, 35, 11],
     [-3, -28, 0, 7, -17],
     [-10, -35, -7, 0, -24],
     [14, -11, 17, 24, 0]]