Issue
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?
Solution
Try:
for i, b in enumerate(bin):
for j, c in enumerate(cost):
a = c + b
res_mat[i][j] = a
Answered By - Ali_Sh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.