1

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?

1 Answer 1

2

Try:

for i, b in enumerate(bin):
    for j, c in enumerate(cost):
        a = c + b
        res_mat[i][j] = a
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.