From 71a2b4a05781d50e24401941f983035ed69be5f4 Mon Sep 17 00:00:00 2001 From: array-in-a-matrix Date: Tue, 22 Nov 2022 20:09:25 -0500 Subject: [PATCH] dot product proc --- src/main.nim | 22 ++++++---------------- src/procedures.nim | 29 ++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/src/main.nim b/src/main.nim index f467c99..028d4cc 100644 --- a/src/main.nim +++ b/src/main.nim @@ -32,31 +32,21 @@ var m2 = newSeqWith(r2, newSeq[float](c2)) procedures.fillMatrix(m2, r2, c2) -var r, c: int -# TODO: calculate dot product (in procedures) -if c1 == r2: - c = c2 - r = r1 -else: - quit "Matrix dimensions mismatched, operation invalid!", QuitFailure +# calculate dot product (in procedures) -var m = newSeqWith(r, newSeq[float](c)) - -for i in countup(0, r1-1): - for j in countup(0, c2-1): - for k in countup(0, c1-1): - m[i][j] = m[i][j] + m1[i][k] * m2[k][j] +var m = newSeqWith(0, newSeq[float](0)) +m = dot(m1, m2) # TODO: calculate cross product (in procedures) echo "\nFirst matrix is:" -procedures.printMatrix(m1, r1) +procedures.printMatrix(m1) echo "\nSecond matrix is:" -procedures.printMatrix(m2, r2) +procedures.printMatrix(m2) echo "\nResult matrix is:" -procedures.printMatrix(m, r) \ No newline at end of file +procedures.printMatrix(m) \ No newline at end of file diff --git a/src/procedures.nim b/src/procedures.nim index 7a85a4c..890ca57 100644 --- a/src/procedures.nim +++ b/src/procedures.nim @@ -1,7 +1,8 @@ -import strutils +import strutils, sequtils ## prints a matrix to the standard output -proc printMatrix*(matrix: seq[seq[float]], row: int) = +proc printMatrix*(matrix: seq[seq[float]]) = + let row: int = matrix.len for i in countup(1, row): echo matrix[i-1] @@ -13,4 +14,26 @@ proc fillMatrix*(matrix: var seq[seq[float]], row, col: int) = var entry: float = parseFloat(readLine(stdin)) matrix[i-1].add(entry) matrix[i-1].delete(0) - echo matrix[i-1] \ No newline at end of file + echo matrix[i-1] + +## calculate dot product +proc dot*(matrix1: seq[seq[float]], matrix2: seq[seq[float]]): seq[seq[float]] = + let col1: int = matrix1.len + let row1: int = matrix1[0].len + let col2: int = matrix2.len + let row2: int = matrix2[0].len + var col, row: int + + if col1 == row2: + col = col2 + row = row1 + else: + quit "Matrix dimensions mismatched, operation invalid!", QuitFailure + + var matrix = newSeqWith(row, newSeq[float](col)) + + for i in countup(0, row1-1): + for j in countup(0, col2-1): + for k in countup(0, col1-1): + matrix[i][j] = matrix[i][j] + matrix1[i][k] * matrix2[k][j] + return matrix \ No newline at end of file