How to implement matrix multiplication in TypeScript

1 Answer

0 votes
// Multiply rows of A by columns of B.

// A 2D matrix of numbers
type Matrix = number[][];

// Print a 2D array (matrix)
function printMatrix(arr2d: Matrix): void {
  for (let i: number = 0; i < arr2d.length; i++) {
    let row: string = "";
    for (let j: number = 0; j < arr2d[i].length; j++) {
      row += arr2d[i][j].toString().padStart(4, " ");
    }
    console.log(row);
  }
}

// Multiply matrices A and B into C
function multipleMatrix(a: Matrix, b: Matrix, c: Matrix): void {
  for (let i: number = 0; i < c.length; i++) {
    for (let j: number = 0; j < c[i].length; j++) {
      for (let k: number = 0; k < a[i].length; k++) {
        c[i][j] += a[i][k] * b[k][j];
      }
    }
  }
}

// Create matrices
const a: Matrix = [
  [1, 8, 5],
  [6, 7, 1],
  [8, 7, 6]
];

const b: Matrix = [
  [4, 8, 1],
  [6, 5, 3],
  [4, 6, 5]
];

// Initialize result matrix C with zeros
const c: Matrix = Array.from({ length: a.length }, (): number[] =>
  Array(b[0].length).fill(0)
);

// c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])

printMatrix(a);
console.log();
printMatrix(b);
console.log();

multipleMatrix(a, b, c);

printMatrix(c);



/*
run:
        
     1   8   5
     6   7   1
     8   7   6
    
     4   8   1
     6   5   3
     4   6   5
    
    72  78  50
    70  89  32
    98 135  59
    
*/


 



answered May 25 by avibootz
...