How to resolve the algorithm Matrix multiplication step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Matrix multiplication step by step in the Nim programming language

Table of Contents

Problem Statement

Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Matrix multiplication step by step in the Nim programming language

Source code in the nim programming language

import strfmt

type Matrix[M, N: static[int]] = array[M, array[N, float]]

let a = [[1.0,  1.0,  1.0,   1.0],
         [2.0,  4.0,  8.0,  16.0],
         [3.0,  9.0, 27.0,  81.0],
         [4.0, 16.0, 64.0, 256.0]]

let b = [[    4.0, -3.0  ,  4/3.0,   -1/4.0],
         [-13/3.0, 19/4.0, -7/3.0,  11/24.0],
         [  3/2.0, -2.0  ,  7/6.0,   -1/4.0],
         [ -1/6.0,  1/4.0, -1/6.0,   1/24.0]]

proc `$`(m: Matrix): string =
  result = "(["
  for r in m:
    if result.len > 2: result.add "]\n ["
    for val in r: result.add val.format("8.2f")
  result.add "])"

proc `*`[M, P, N](a: Matrix[M, P]; b: Matrix[P, N]): Matrix[M, N] =
  for i in result.low .. result.high:
    for j in result[0].low .. result[0].high:
      for k in a[0].low .. a[0].high:
        result[i][j] += a[i][k] * b[k][j]

echo a
echo b
echo a * b
echo b * a


  

You may also check:How to resolve the algorithm Pinstripe/Display step by step in the Delphi programming language
You may also check:How to resolve the algorithm Power set step by step in the Bracmat programming language
You may also check:How to resolve the algorithm Interactive programming (repl) step by step in the Wren programming language
You may also check:How to resolve the algorithm Zeckendorf number representation step by step in the Haskell programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the SuperCollider programming language