How Python implements code examples for matrix classes

Source: Internet
Author: User
This article mainly introduced the Python implementation of the Matrix class, combined with a complete example of the definition of Python matrix, calculation, conversion and other related operational skills, the need for friends can refer to the following

The examples in this article describe the matrix classes implemented by Python. Share to everyone for your reference, as follows:

Scientific computation is inseparable from the operation of matrices. Of course, Python already has a very good off-the-shelf library:numpy(numpy simple installation and use

I'm writing this matrix class, not going to reinvent a wheel, just as an exercise, recorded here.

Note: The function of this class has not all realized, slowly in perfect it.

All code:


Import Copyclass Matrix: "Matrix Class" Def __init__ (self, row, column, fill=0.0): Self.shape = (row, column) Self.row = Row self.column = Column Self._matrix = [[Fill]*column for I in Range] # returns the value of element m (i, J): M[i, j] def __getit      Em__ (self, index): If Isinstance (index, int): return self._matrix[index-1] elif isinstance (index, tuple): return Self._matrix[index[0]-1][index[1]-1] # Sets the value of element m (i,j) to S:m[i, j] = s def __setitem__ (self, Index, value): if ISI Nstance (index, int): self._matrix[index-1] = copy.deepcopy (value) elif isinstance (index, tuple): Self._matrix [Index[0]-1]  [Index[1]-1] = value def __eq__ (self, N): ' Equal ' ' # A = = B assert isinstance (N, Matrix), "Type mismatch, cannot compare" return N.shape = = Self.shape # comparison dimension, can be modified to another Def __add__ (self, N): ' Add ' ' # A + B Assert n.shape = = Self.shape, "Dimension not a horse  Match, cannot add "M = Matrix (Self.row, Self.column) for R in range (Self.row): A C in range (Self.column): M[r, C] = Self[r, C] + N[r, C] return m def __sub__ (self, N): "Subtraction" # A-b assert n.shape = = Self.shape, "Dimension mismatch, cannot subtract" m = Matrix (Self.row, Self.column) for R in range (Self.row): for C in range (Self.column): M[r, c] = Self[r, c] -N[r, C] return M def __mul__ (self, N): ' Multiplication ' ' # A * B (or: A * 2.0) if isinstance (N, int) or isinstance (n,f          Loat): M = Matrix (Self.row, Self.column) for R in range (Self.row): for C in range (Self.column): M[r, c] = self[r, c]*n else:assert n.row = = Self.column, "Dimension mismatch, cannot be multiplied" M = Matrix (Self.row, N.column) fo            R r in range (Self.row): for C in range (n.column): sum = 0 for k in range (Self.column): Sum + = Self[r, K] * n[k, R] m[r, c] = sum return M def __p__ (self, N): ' Division ' ' # A/b pass def _ _pow__ (self, k): "' exponentiation ' ' # a**k assert self.row = = Self.column," Not a phalanx, cannot be exponentiation "M = Copy.deepcopy (self) for I In range (k): M = m* Self return M def rank (self): ' The rank of the Matrix ' ' Pass def Trace (self): ' The trace of the Matrix ' ' Pass def adjoint (self): ' ' Adjoint matrix ' pass def invert (self): ' Inverse matrix ' ' assert self.row = = Self.column, ' not phalanx ' M = Matrix (Self.row, SELF.C      olumn*2) I = self.identity () # Unit matrix i.show () ############################# # Stitching for R in range (1,M.ROW+1):     temp = Self[r] Temp.extend (I[r]) m[r] = copy.deepcopy (temp) m.show () ############################# # Elementary Line transformation for R in range (1, m.row+1): # Bank first Element (M[r, R]) if 0, the nearest current column element is swapped downward if m[r, r] = = 0:for rr in range (r +1, m.row+1): If M[RR, r]! = 0:M[R],M[RR] = m[rr],m[r] # Swap two lines break assert M[r, r]! = 0        , ' Matrix irreversible ' # Bank first element (M[r, R]) to 1 temp = m[r,r] # cache for C in range (R, m.column+1): M[r, c]/= Temp        Print ("m[{0}, {1}]/= {2}". Format (r,c,temp)) m.show () # All elements on and below this column are 0 for RRS in range (1, m.row+1): temp = M[RR, r] # slowSave for C in range (R, m.column+1): if rr = = R:continue M[RR, c]-= temp * m[r, C] Print ("m[{0}, {1}]-= {2} * m[{3}, {1}]". Format (RR, C, Temp,r)) m.show () # intercept inverse matrix N = Matrix (self.row,self . column) for R in range (1,SELF.ROW+1): n[r] = M[r][self.row:] return N def jieti (self): ' line simplifies ladder matrix ' pa SS Def transpose (self): ' transpose ' M = Matrix (Self.column, Self.row) for R in range (Self.column): for C in RA  Nge (Self.row): M[r, c] = Self[c, R] return M def cofactor (self, Row, column): "Algebra cofactor type (for determinant expansion) ' assert  Self.row = = Self.column, "Not a phalanx, unable to calculate algebraic cofactor" assert Self.row >= 3, "at least 3*3 order matrix" assert row <= self.row and column        <= Self.column, "Subscript out of range" M = Matrix (self.column-1, self.row-1) for R in range (Self.row): if r = = row:         Continue for C in range (Self.column): if c = = Column:continue rr = r-1 if R > row Else r CC = C-1 if C &GT Column Else C m[rr, cc] = Self[r, c] return M def det (self): ' Calculate determinant (determinant) ' ' assert self.row = =  Self.column, "Non-determinant, cannot be computed" if self.shape = = (2,2): return self[1,1]*self[2,2]-self[1,2]*self[2,1] Else:sum =  0.0 for C in range (self.column+1): Sum + = ( -1) * * (c+1) *self[1,c]*self.cofactor (1,c). Det () return sum def  Zeros (self): ' All 0 matrices ' ' m = Matrix (Self.column, Self.row, fill=0.0) return M def ones (self): ' All 1 matrices ' m = Matrix (Self.column, Self.row, fill=1.0) return M def identity (self): ' Unit matrix ' ' assert self.row = = Self.colum        N, "non-n*n matrix, no unit matrix" M = Matrix (Self.column, Self.row) for R in range (Self.row): for C in range (Self.column): M[r, C] = 1.0 if R = = C Else 0.0 return M def show (self): ' Print matrix ' for R in range (Self.row): for C in  Range (Self.column): Print (self[r+1, c+1],end= ") print () if __name__ = = ' __main__ ': M = Matrix (3,3,fill=2.0) n = Matrix (3,3,fill=3.5) M[1] = [1.,1.,2.]  M[2] = [1.,2.,1.]  M[3] = [2.,1.,1.] p = m * N q = m*2.1 r = m**3 #r. Show () #q. Show () #print (p[1,1]) #r = M.invert () #s = r*m print () m.show () print ( ) #r. Show () print () #s. Show () print () print (M.det ())

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.