Home > Back-end >  i need help creating a function of add two matrices and return the sum matrix
i need help creating a function of add two matrices and return the sum matrix

Time:11-23

The below code looks to be error free to me at least. But I'm not getting the output I want, but if i dont use the function and add the two of them directly with the same syntax, I'm getting the correct answer. pls help


a = [[1,1],[2,2]]    #first matrix
b = [[4,4],[3,3]]    #second matrix

#creating a function to add to two matrices and return the sum
def sum(m,n):
    o = [[0,0],[0,0]]
    for i in range(2):
        for j in range(2):
            o[i][j] = m[i][j]   n[i][j]
            return o

ans = sum(a,b)
print(ans)

this is giving the following answer output:

[[5, 0], [0, 0]]

where as the output should be : [[5, 5], [5, 5]]

CodePudding user response:

Can you make sure the return statement is given outside both the for loops?.

Seems like you have given the return statement inside for loop of j, So It's calculating just one sum and returning

def sum(m,n): 
o = [[0,0],[0,0]] 
for i in range(2): 
    for j in range(2): 
        o[i][j] = m[i][j]   n[i][j] 
return o

return should be given like this, then it'll give

[[5, 5], [5, 5]]

CodePudding user response:

You can use the module numpy to add matrices together.

First install the module using "pip install numpy" for windows or "pip3 install numpy" for linux. Then, in your code, run

import numpy
numpy.add(list1, list2)

CodePudding user response:

You can use a list comprehension:

def sum_matrices(a, b):
    return [[a[i][j]   b[i][j] for j in range(len(a[i]))] for i in range(len(a))]

Or you can use numpy:

import numpy as np

def sum_matrices(a, b):
    return np.add(a, b).tolist()
  • Related