Q:

Python program to illustrate Matrix Addition using Class

0

Matrix in python is a two-dimensional data structure which is an array of arrays.

Example:

matrix example

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to create and add matrix in Python using class

class Matrix:
    def getValues(self,row,col):
        self.__M=[]
        for i in range(row):
            C=[]
            for j in range(col):
                C.append(int(input("Enter Value [{}][{}]:".format(i,j))))
            self.__M.append(C)

    def printMatrix(self):
         for r in self.__M:
             for c in r:
                 print(c,end=' ')
             print()

    def __add__(self, T):
        R=Matrix()
        R.__M=[]
        for i in range(len(self.__M)):
            C=[]
            for j in range(len(self.__M[i])):
                C.append(self.__M[i][j]+T.__M[i][j])
            R.__M.append(C)
        return R

print("Matrix 1 : ")
mat1 = Matrix()
mat1.getValues(3,3)
mat1.printMatrix()

print("Matrix 2 : ")
mat2 = Matrix()
mat2.getValues(3,3)
mat2.printMatrix()

mat3=mat1 + mat2

print("Addition Matrix : ")
mat3.printMatrix()

Output:

Matrix 1 : 
Enter Value [0][0]:4
Enter Value [0][1]:6
Enter Value [0][2]:8
Enter Value [1][0]:2
Enter Value [1][1]:5
Enter Value [1][2]:36
Enter Value [2][0]:3
Enter Value [2][1]:46
Enter Value [2][2]:2
4 6 8 
2 5 36 
3 46 2 
Matrix 2 : 
Enter Value [0][0]:0
Enter Value [0][1]:5
Enter Value [0][2]:2
Enter Value [1][0]:5
Enter Value [1][1]:6
Enter Value [1][2]:1
Enter Value [2][0]:7
Enter Value [2][1]:4
Enter Value [2][2]:4
0 5 2 
5 6 1 
7 4 4 
Addition Matrix : 
4 11 10 
7 11 37 
10 50 6 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now