115 two matrices Write a function to add two matrices The he

11.5 two matrices Write a function to add two matrices. The head the function is: er of def addMatrix (a, b): In order to be added, the two matrices must have the same dimensions and the same or compatible types of elements. Let c be the resulting matrix. Each element c is a by For example, for two 3 x 3 matrices a and b, c is

Solution

Here goes the required function for adding the two matrices using python language

def addMatrix(a, b):
    if(len(a)!=len(b) || len(a[0])!=len(b[0])){
        return \"Matrices cannot be added\"
    }else{
        c = []
        for i in range(len(a)):
            row = []
            for j in range(len(a[0])):
                row.append(a[i][j]+b[i][j])
            c.append(row)
        return c
    }

*You can calculate the number of rows in the matrix using len() function. eg: len(a) gives you the number of rows in a and len(b) will give you the number of columns in b.

*similarly len(a[0]) will give you the number of columns in a and len(b[0]) will give you the number of columns in b.

*You first check if both the arrays have same number of rows and columns using len(a)!=len(b) || len(a[0])!=len(b[0])

which means if a and b doesn\'t have the same number of rows or a and b doesn\'t have the same number of columns then return \"Matrices cannot be added\" else add the matices and return the matrix \'c\'.

 11.5 two matrices Write a function to add two matrices. The head the function is: er of def addMatrix (a, b): In order to be added, the two matrices must have

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site