Home > Software engineering >  Adding two numbers from list and assigning the output to a matrix
Adding two numbers from list and assigning the output to a matrix

Time:10-24

I'm trying to add two numbers from a list and assign the addition of two numbers to a matrix in Python.I tried like this below

import numpy as np

#Create bin and cost list
bin = [10, 20]
cost = [10, 20]

# Create a result matrix of 2 x 2
res_mat = [[0.0 for i in range(len(bin))] for j in range(len(cost))]

for b in bin:
    for c in cost:
        for i in range(len(bin)):
            for j in range(len(cost)):
                a = c   b 
                res_mat[i][j] = a

print(np.array(res_mat))   #Print the final result matrix

When I print the res_mat I get the matrix like below :

[[40 40]
 [40 40]]

While I'm expecting the correct matrix like below :

[[20 30]
 [30 40]]

So what change should be made so that the matrix correctly displays the result?

CodePudding user response:

Try:

for i, b in enumerate(bin):
    for j, c in enumerate(cost):
        a = c   b
        res_mat[i][j] = a
  • Related