Overview

Matrix Mult

Matrix multiplication using 1D array.

Source Code

// Matrix multiplication using 1D array.
type TMatrix = record Data: array of Float; Rows, Cols: Integer; end;
function CreateMatrix(r, c: Integer; const d: array of Float): TMatrix;
begin Result.Rows := r; Result.Cols := c; Result.Data := d; end;
function MatrixMultiply(const A, B: TMatrix): TMatrix;
var i, j, k: Integer;
begin
  Result.Rows := A.Rows; Result.Cols := B.Cols;
  Result.Data.SetLength(A.Rows * B.Cols);
  for i := 0 to A.Rows - 1 do
    for j := 0 to B.Cols - 1 do begin
      var sum := 0.0;
      for k := 0 to A.Cols - 1 do sum += A.Data[i * A.Cols + k] * B.Data[k * B.Cols + j];
      Result.Data[i * Result.Cols + j] := sum;
    end;
end;
var A := CreateMatrix(2, 2, [1.0, 2.0, 3.0, 4.0]);
var B := CreateMatrix(2, 2, [5.0, 6.0, 7.0, 8.0]);
var C := MatrixMultiply(A, B);
PrintLn('C[0,0] = ' + C.Data[0].ToString(1));

Result

C[0,0] = 19.0
On this page