SquareMatrix.st
author Claus Gittinger <cg@exept.de>
Sat, 02 May 2020 21:40:13 +0200
changeset 5476 7355a4b11cb6
parent 5123 0a006004102a
permissions -rw-r--r--
#FEATURE by cg class: Socket class added: #newTCPclientToHost:port:domain:domainOrder:withTimeout: changed: #newTCPclientToHost:port:domain:withTimeout:

"{ Encoding: utf8 }"

"{ Package: 'stx:libbasic2' }"

"{ NameSpace: Smalltalk }"

TwoDimensionalMatrix variableSubclass:#SquareMatrix
	instanceVariableNames:''
	classVariableNames:''
	poolDictionaries:''
	category:'Collections-MultiDimensional'
!


!SquareMatrix class methodsFor:'instance creation'!

withAll:elements
    |numElements nRows|

    numElements := elements size.
    nRows := numElements integerSqrt.
    self assert:(nRows * nRows == numElements) description:'number of elements is not square'.
    ^ (self new:numElements) 
        replaceFrom:1 with:elements;
        setDimensions:{nRows . nRows }

    "
     Matrix3_3  withAll:#(11 12 13 21 22 23 31 32 33) 
    "
! !

!SquareMatrix methodsFor:'matrix operations'!

determinant
    "Answer the determinant of this matrix.

    Note that if your only interest in the determinant is to decide whether or not the matrix is singular,
    you're better off using #isSingular which is not subject to numeric overflow."

    ^ self determinantByLuDecomposition

    "
     (Matrix identity:3) determinantByCofactors
    "
!

determinantByCofactors
    "Answer the determinant of this matrix."

    dimensions = #( 1 1 ) ifTrue: [ ^ self _at: 1 at: 1 ].

    "General case"

    ^(1 to: self columns) 
            inject: 0 
            into: [ :tot :c | tot + ((self _at: 1 at: c) * (self cofactor: 1@c)) ]
!

determinantByLuDecomposition
        "Answer the determinant of a matrix."

        | lu prod |

        lu := self luForm.
        prod := self luForm rowInterchangeSign.

        1 to: lu rows do: [ :i |
                (lu at: i at: i) <= lu comparisonTolerance ifTrue: [ ^0 ].
                prod := prod * (lu at: i at: i) asFraction ].

        ^prod
! !

!SquareMatrix methodsFor:'queries'!

isSquare
    ^ true
! !

!SquareMatrix class methodsFor:'documentation'!

version_CVS
    ^ '$Header$'
! !