Python matrix instances

Source: Internet
Author: User

Python matrix instances

This example describes the matrix class implemented by Python. We will share this with you for your reference. The details are as follows:

Scientific Computing is inseparable from matrix calculation. Of course, python already has a very good ready-made Library: numpy (simple installation and use of numpy can refer to http://www.bkjia.com/article/66236.htm ).

I am writing this matrix class, instead of recreating a wheel, just as an exercise, recorded here.

Note: The functions of this class have not been fully implemented yet. Please gradually improve them.

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 (row)] # Return the value of the element m (I, j): m [I, j] def _ getitem _ (self, index): if isinstance (index, int): return self. _ matrix [index-1] elif isinstance (index, tuple): return self. _ matrix [index [0]-1] [index [1]-1] # set the value of element m (I, j) to s: m [I, J] = s def _ setitem _ (self, index, value): if isinstance (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 # Compare dimension, which can be changed to another def _ add _ (self, N): '''add''' # A + B assert N. shape = self. shape, "dimensions do not match, cannot be added" 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 _ sub _ (self, N ): ''' subtraction ''' # A-B assert N. shape = self. shape, "dimensions do not match, 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 isinst Ance (N, int) or isinstance (N, float): 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 does not match, cannot be multiplied" M = Matrix (self. row, N. column) for 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 _ div _ (self, N): ''' division '''# A/B pass def _ pow _ (self, k): ''' multiplication ''' # A ** k assert self. row = self. column, "not a square matrix, not a square" M = copy. deepcopy (self) for I in range (k): M = M * self return M def rank (self): ''' rank of the matrix ''' pass def trace (self): '''matrix trace ''' pass def adjoint (self): ''' adjoint matrix ''' pass def invert (self ): '''inverse matrix ''' assert self. row = self. column, "not a square Matrix" M = Matrix (self. row, self. column * 2) I = self. identity () # unit matrix I. show ()### ######################### Splice for r in range (1, M. row + 1): temp = self [r] temp. extend (I [r]) M [r] = copy. deepcopy (temp) M. show () ############################ transform primary rows for r in range (1, m. row + 1): # if the first element of the row (M [r, r]) is 0, the first element of the current column is switched 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] # exchange two rows of break assert M [r, r]! = 0, 'matrix irreversible '# convert the first element (M [r, r]) of the row 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 in this column and below are converted to 0 for rr in range (1, M. row + 1): temp = M [rr, r] # cache 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 () # truncation 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): ''' the row simplification step matrix ''' pass def transpose (self ): '''transpose ''' M = Matrix (self. column, self. row) for r in range (self. column): for c in range (self. row): M [r, c] = self [c, r] return M def cofactor (self, row, column): ''''algebraic remainder formula (used to expand the determinant) '''assert self. row = self. column, "not a square matrix, cannot calculate the algebra remainder" assert self. row> = 3, "at least three X three-level phalanx" 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> column else c M [rr, cc] = self [r, c] return M def det (self): ''' determinant ''' assert self. row = self. column, "non-determinant, cannot calculate" if self. shape = (0.0): return self [] * self []-self [] * self [] else: sum = 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 zero 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. column, "non-n * n Matrix, non-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 (m. det ())

Related Article

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.