diff --git a/src/matrix.nim b/src/matrix.nim new file mode 100644 index 0000000..30cb819 --- /dev/null +++ b/src/matrix.nim @@ -0,0 +1,255 @@ +import strformat +from "./tuple" import `=~` + +type + Matrix* = object + matrix: seq[float] + width: int + height: int + MatrixInitialisationException = object of CatchableError + MatrixMultiplicationException = object of CatchableError + IdentityMatrixCreationError = object of CatchableError + MatrixInversionError = object of CatchableError + +proc matrix(width, height: int): Matrix = + result.matrix = newSeq[float](width * height) + result.width = width + result.height = height + +proc matrix*(data: seq[float], width, height: int): Matrix = + if len(data) != width * height: + raise newException(MatrixInitialisationException, &"Matrix dimensions did not match size of input data sequence, wanted {width * height} but it was {len(data)}") + result.matrix = data + result.width = width + result.height = height + +template `[]`*(mat: Matrix, row, column: int): float = mat.matrix[row * mat.width + column] +template `[]=`*(mat: var Matrix, row, column: int, val: float) = mat.matrix[row * mat.width + column] = val + +proc `==`*(lhs, rhs: Matrix): bool = + if lhs.width != rhs.width or lhs.height != rhs.height: return false + for i in 0..