Tuesday, October 4, 2022

Matrices in Python without Numpy: Part 2

Matrices in Python without Numpy:  Part 2


Let's continue from yesterday.  


Screenshots are made using an emulator on my.numworks.com. 


Matrix Addition


madd(matrix 1, matrix 2)


Adds matrix 1 to matrix 2.  The dimensions of both matrices must be the same.


def madd(A,B):

  # dimension check

  if len(A) != len(B) or len(A[0]) != len(B[0]):

    return "Dimensions of A and B mismatch"

  else:

    M=newmatrix(len(A),len(A[0]))

    for i in range(len(A)):

      for j in range(len(A[0])):

        M[i][j]=A[i][j]+B[i][j]

    return M


In this example screen shot:


mat1 = [ [ 8, -2 ], [ -4, 7 ] ]

mat2 = [ [ 1, 3 ], [ 5, 6 ] ]


Matrix addition is communitive.  Hence,  mat1 + mat2 = mat2 + mat1.





Matrix Multiplication


mmult(mat1, mat2)


Multiplies mat1 to mat2.  Here the number of columns of mat1 must be the same as the rows of mat2.  


Matrix multiplication is not communitive.  Hence, mat1 * mat2 ≠ mat2 * mat1


def mmult(A,B):

  # dimension check

  if len(A[0]) != len(B):

    return "Columns of A != Rows of B"

  else:

    M=newmatrix(len(A),len(B[0]))

    for i in range(len(A)):

      for j in range(len(B[0])):

        t=0

        for k in range(len(A[0])):

          t +=A[i][k]*B[k][j]

        M[i][j]=t

    return M



Note that both madd and mmult require newmatrix.  See yesterday's post for the code for newmatrix. 


Next time, we will work with determinants and inverses.


Happy computing,


Eddie 



Source:


Ives, Thom.  "BASIC Linear Algebra Tools in Pure Python without Numpy or Scipy"  Integrated Machine Learning & AI  December 11, 2018.  https://integratedmlai.com/basic-linear-algebra-tools-in-pure-python-without-numpy-or-scipy/


All original content copyright, © 2011-2022.  Edward Shore.   Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited.  This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author. 


  Casio fx-7000G vs Casio fx-CG 50: A Comparison of Generating Statistical Graphs Today’s blog entry is a comparison of how a hist...