Thursday, October 6, 2022

Matrices in Python without Numpy: Part 4

Matrices in Python without Numpy:  Part 4


We have a good set of tools through out the first three parts.  


For today's blog, let mat1 = [ [ 2, -3, 4 ], [ 1, 5, 7 ] [ 4, 8, -6 ] ]


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



Row Multiply and Add


rowop(matrix, row1, scalar, row2)


Multiplies row1 by a scalar and adds the results to row2.  The matrix is permanently changed.


def rowop(M,r1,s,r2):

  c=len(M[0])

  MT=M

  for k in range (c):

    MT[r2][k]=MT[r1][k]*s+MT[r2][k]

  return MT





Upper Triangle Matrix


utri(matrix)


Changes the matrix to an upper triangular form.  All the elements below the diagonals are zero.  Due to the algorithm, row 0 cannot have a zero or an error occurs.  The algorithm is not perfect.  


def utri(M):

  MT=M

  c=len(M[0])

  for j in range(c-1):

    for k in range(j+1,c):

      rowop(MT,j,-MT[k][j]/MT[j][j],k)

  return MT





Determinant Using the Upper Triangle Matrix


det(matrix)


Calculates the determinant by first transforming the matrix into an upper triangle matrix.


def det(M):

  MT=utri(M)

  d=1

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

    d*=MT[k][k]

  return d


Please be aware that floating point limitations of Python. 





The determinant should be -322. 



This concludes the series.  


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. 


TI 84 Plus CE: Consolidated Debts

TI 84 Plus CE: Consolidated Debts   Disclaimer: This blog is for informational and academic purposes only. Financial decisions are your ...