Matrix Multiplication, Transpose and a lot more…

Have you done matrix multiplication? Quite tedious right? Becomes boring when a big matrix is place in front of you…

So this code is going to do the same. But wait you don’t need to take out your copy and pen, just sit back and watch the program do it for you…

Here’s the code. Paste it in a file and save it as Matrix.py


#Matrix.py
from sys import stderr as rprt

 
class Matrix:
    '''A class for creation of matrices'''
    def __init__(self, *args):
        self.mtx = [ ]
        self.rows = args[0]
        if self.check_mtx() == 'fine':
            self.cols = self.get_cols()
         
    def __str__(self):   
       return 'A '+str(len(self.rows))+'*'+str(len(self.cols))+' matrix'
    
    def get_cols(self):
        i = 0
        cols = [ ]
        col = [ ]
        while i < len(self.rows[0]):
            col = [ ]
            for j in range(len(self.rows)):
                col.append(self.rows[j][i])
            cols.append(col)
            i += 1
        return cols
         
    def check_mtx(self):
        num = len(self.rows[0])
        for i in self.rows:
            if len(i) != num: 
                self.report_error('Invalid Matrix')
                break
        else: 
            return 'fine'
             
    def show(self):
        for i in self.rows:
            print(*i)
             
    def transpose(self):
        return Matrix(self.cols)
       
    def report_error(self, error):
        rprt.write(error+'\n')

    def __check_mtx_add(self, mtx2):
        rows1 = len(self.rows)
        rows2 = len(mtx2.rows)
        cols1 = len(self.rows[0])
        cols2 = len(mtx2.rows[0])
        if rows1 == rows2 and cols1 == cols2:
            return 'fine'
        else:
            report_error('Orders do not match!')

    def __eq__(self, mtx2):
        if self.rows == mtx2.rows:
            return True
        else:
            return False

    def __add__(self, mtx2):
        if self.__check_mtx_add(mtx2) == 'fine':
            new = []
            for i in range(len(self.rows)):
                row = [ ]
                for j in range(len(self.cols)):
                    elem = self.rows[i][j] + mtx2.rows[i][j]
                    row.append(elem)
                new.append(row)
            return Matrix(new) 
                
    def __check_mtx_mul(self, mtx2):
        rows1 = len(self.rows)
        rows2 = len(mtx2.rows)
        cols1 = len(self.rows[0])
        cols2 = len(mtx2.rows[0])
        if cols1 == rows2:
            return 'fine' 
         
    def __mul__(self, mtx2):
        if self.__check_mtx_mul(mtx2) == 'fine':
             iteri = 0
             iterj = 0
             product = [ ]
             while iterj < len(self.rows):
                 row = [ ]
                 while iteri < len(mtx2.cols):
                     elem = 0
                     r = self.rows[iterj]
                     c = mtx2.cols[iteri]
                     for i in range(len(r)):
                         k = r[i] * c[i]
                         elem += k  
                     row.append(elem)
                     iteri += 1
                 product.append(row)
                 iterj += 1
                 iteri = 0    
             return Matrix(product)        
        else:
            self.report_error(' Invalid multiplication!')        

Save the below code given as Sq_Matrix.py in the same directory/folder as that of Matrix.py. Ok.

from Matrix import Matrix

class SqMtx(Matrix):
    '''A class for designing Square Matrices'''
    def __init__(self, *args):
        Matrix.__init__(self, args[0])
        self.I = self.get_Identity('+ve')
        self.nI = self.get_Identity('-ve')

    def get_Identity(self, mag):
        if mag == '-ve':
            k = -1
        else:
            k = 1
        I = [ ]
        for i in range(len(self.cols)):
            row = [ ] 
            for j in range(len(self.cols)):
                if i == j:
                    row.append(k)
                else:
                    row.append(0)
            I.append(row)
        return Matrix(I)

    def check_symm(self):
        if self.rows == self.cols:
            print('Symmetric Matrix')
        else:
            self.report_error('Not Symmetric!')

    def give_symm_mtx(self, mag = 'sym'):
        trans = self.transpose()
        new = [ ]
        if mag == 'skew':
            k = -1
        else:
            k = 1
        for i in range(len(self.rows)):
            row = [ ]
            for j in range(len(self.cols)):
                row.append(self.rows[i][j] + k*trans.rows[i][j])
            new.append(row)
        return Matrix(new)

    def check_skewsymm(self):
        if self == self*self.nI:
            print('Skew-Symmetric matrix!')
        else:
            self.report_error('Not a skew-symmetric matrix!')

    def __pow__(self, exp):
        if exp.__class_.__name__ == 'int':
            if exp > 0 :
            new = self.I 
                for i in range(exp):
                    new = self*new
                return new
            elif exp == 0:
                return self.I
        else:
            self.report_error('Sorry! Can not raise the matrix to a fractional power!')

Now do whatever you want or run the below code in a file named main.py in the same folder to get a better view of the code.

Hope you enjoy this. Matrix operations might become easy with this but you need to do it in Mathematics as well, Okay!

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free