Made more Matrix operations exportable
This commit is contained in:
parent
b27ff44e1c
commit
1d87ef2303
@ -61,19 +61,19 @@ proc `*`*(lhs: Matrix, rhs: Tuple4): Tuple4 = (lhs * matrix(rhs)).toTuple4()
|
||||
|
||||
template isSquare(mat: Matrix): bool = mat.height == mat.width and len(mat.matrix) == (mat.height * mat.width)
|
||||
|
||||
proc identity(size: int): Matrix =
|
||||
proc identity*(size: int): Matrix =
|
||||
result.width = size
|
||||
result.height = size
|
||||
result.matrix = newSeq[float](size * size)
|
||||
for i in 0..<size:
|
||||
result[i, i] = 1.0
|
||||
|
||||
proc identity(mat: Matrix): Matrix =
|
||||
proc identity*(mat: Matrix): Matrix =
|
||||
if not isSquare(mat):
|
||||
raise newException(IdentityMatrixCreationError, "Can only create an identity for a square matrix")
|
||||
result = identity(mat.height)
|
||||
|
||||
proc transpose(mat: Matrix): Matrix =
|
||||
proc transpose*(mat: Matrix): Matrix =
|
||||
result.width = mat.height
|
||||
result.height = mat.width
|
||||
result.matrix = newSeq[float](result.width * result.height)
|
||||
@ -81,8 +81,8 @@ proc transpose(mat: Matrix): Matrix =
|
||||
for i in 0..<mat.width:
|
||||
result[i, j] = mat[j, i]
|
||||
|
||||
proc cofactor(mat: Matrix, row, col: int): float
|
||||
proc determinant(mat: Matrix): float =
|
||||
proc cofactor*(mat: Matrix, row, col: int): float
|
||||
proc determinant*(mat: Matrix): float =
|
||||
if mat.width == 2 and mat.height == 2:
|
||||
result = mat.matrix[0] * mat.matrix[3] - mat.matrix[1] * mat.matrix[2]
|
||||
else:
|
||||
@ -91,7 +91,7 @@ proc determinant(mat: Matrix): float =
|
||||
|
||||
template indexToCoordinate(mat: Matrix, index: int): (int, int) = (index div mat.width, index mod mat.width)
|
||||
|
||||
proc submatrix(mat: Matrix, row, col: int): Matrix =
|
||||
proc submatrix*(mat: Matrix, row, col: int): Matrix =
|
||||
result.width = mat.width - 1
|
||||
result.height = mat.height - 1
|
||||
for i in 0..<(mat.width * mat.height):
|
||||
@ -99,15 +99,15 @@ proc submatrix(mat: Matrix, row, col: int): Matrix =
|
||||
if not (row == coordinate[0] or col == coordinate[1]):
|
||||
result.matrix.add(mat.matrix[i])
|
||||
|
||||
proc minor(mat: Matrix, row, col: int): float = mat.submatrix(row, col).determinant
|
||||
proc cofactor(mat: Matrix, row, col: int): float =
|
||||
proc minor*(mat: Matrix, row, col: int): float = mat.submatrix(row, col).determinant
|
||||
proc cofactor*(mat: Matrix, row, col: int): float =
|
||||
result = mat.minor(row, col)
|
||||
if (row + col) mod 2 == 1:
|
||||
result = result * -1
|
||||
|
||||
template isInvertable(mat: Matrix): bool = mat.determinant != 0
|
||||
|
||||
proc inverse(mat: Matrix): Matrix =
|
||||
proc inverse*(mat: Matrix): Matrix =
|
||||
if not isSquare(mat):
|
||||
raise newException(MatrixInversionError, "Can only invert a square matrix")
|
||||
if not isInvertable(mat):
|
||||
|
Loading…
Reference in New Issue
Block a user