SoFunction
Updated on 2024-11-10

Example of a matrix class implemented in Python

This article is an example of a Python implementation of the matrix class. Shared for your reference, as follows:

Scientific computation is inseparable from matrix operations. Of course, python already has very good ready-made libraries:numpy(A simple installation and use of numpy can be found athttps:///article/)

I wrote this matrix class not with the intention of rebuilding a wheel, but just as an exercise, for the record.

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

All code:

import copy
class Matrix:
  '''Matrix class'''
  def __init__(self, row, column, fill=0.0):
     = (row, column)
     = row
     = column
    self._matrix = [[fill]*column for i in range(row)]
  # Return the value of 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] = (value)
    elif isinstance(index, tuple):
      self._matrix[index[0]-1][index[1]-1] = value
  def __eq__(self, N):
    '''Equivalent'''
    # A == B
    assert isinstance(N, Matrix), "Type mismatch, can't compare"
    return  ==  # Compare dimensions, which can be modified to something else
  def __add__(self, N):
    '''Addition'''
    # A + B
    assert  == , "Dimensions don't match, they don't add up."
    M = Matrix(, )
    for r in range():
      for c in range():
        M[r, c] = self[r, c] + N[r, c]
    return M
  def __sub__(self, N):
    '''Subtraction'''
    # A - B
    assert  == , "Dimensions don't match and can't be subtracted."
    M = Matrix(, )
    for r in range():
      for c in range():
        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,float):
      M = Matrix(, )
      for r in range():
        for c in range():
          M[r, c] = self[r, c]*N
    else:
      assert  == , "The dimensions don't match, they can't be multiplied."
      M = Matrix(, )
      for r in range():
        for c in range():
          sum = 0
          for k in range():
            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  == , "It's not a square, you can't multiply it."
    M = (self)
    for i in range(k):
      M = M * self
    return M
  def rank(self):
    '''The rank of the matrix'''
    pass
  def trace(self):
    '''Traces of the Matrix'''
    pass
  def adjoint(self):
    '''Accompanying matrix'''
    pass
  def invert(self):
    '''Inverse matrix'''
    assert  == , "Not a square."
    M = Matrix(, *2)
    I = () # Unit matrix
    ()#############################
    # Splice
    for r in range(1,+1):
      temp = self[r]
      (I[r])
      M[r] = (temp)
    ()#############################
    # Elementary row transformations
    for r in range(1, +1):
      # If the first element of this row (M[r, r]) is 0, swap down to the nearest current row with a non-zero column element
      if M[r, r] == 0:
        for rr in range(r+1, +1):
          if M[rr, r] != 0:
            M[r],M[rr] = M[rr],M[r] # Swap two lines
          break
      assert M[r, r] != 0, 'Matrix Irreversibility'
      # The first element of this line (M[r, r]) is reduced to 1
      temp = M[r,r] # Cache
      for c in range(r, +1):
        M[r, c] /= temp
        print("M[{0}, {1}] /= {2}".format(r,c,temp))
      ()
      # All elements above and below this column are reduced to 0
      for rr in range(1, +1):
        temp = M[rr, r] # Cache
        for c in range(r, +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))
        ()
    # Intercept the inverse matrix
    N = Matrix(,)
    for r in range(1,+1):
      N[r] = M[r][:]
    return N
  def jieti(self):
    '''Row Simplified Step Matrix'''
    pass
  def transpose(self):
    '''Transpose'''
    M = Matrix(, )
    for r in range():
      for c in range():
        M[r, c] = self[c, r]
    return M
  def cofactor(self, row, column):
    '''Algebraic cosine formula (for determinant expansion)'''
    assert  == , "Not a square matrix, can't compute algebraic cosine equations."
    assert  >= 3, "At least a 3*3 order square."
    assert row <=  and column <= , "Subscript out of range"
    M = Matrix(-1, -1)
    for r in range():
      if r == row:
        continue
      for c in range():
        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):
    '''Compute determinant'''
    assert  == ,"Not deterministic, cannot be computed."
    if  == (2,2):
      return self[1,1]*self[2,2]-self[1,2]*self[2,1]
    else:
      sum = 0.0
      for c in range(+1):
        sum += (-1)**(c+1)*self[1,c]*(1,c).det()
      return sum
  def zeros(self):
    '''All-zero matrix'''
    M = Matrix(, , fill=0.0)
    return M
  def ones(self):
    '''All 1 Matrix'''
    M = Matrix(, , fill=1.0)
    return M
  def identity(self):
    '''Unit matrix'''
    assert  == , "Non-n*n matrices, unitless matrices."
    M = Matrix(, )
    for r in range():
      for c in range():
        M[r, c] = 1.0 if r == c else 0.0
    return M
  def show(self):
    '''Print Matrix'''
    for r in range():
      for c in range():
        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
  #()
  #()
  #print(p[1,1])
  #r = ()
  #s = r*m
  print()
  ()
  print()
  #()
  print()
  #()
  print()
  print(())

More about Python related content can be viewed on this site's topic: theSummary of Python mathematical operations techniques》、《Python Regular Expression Usage Summary》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.