Linear algebra in Pascal
last modified November 19, 2026 Free Pascal 3.2.2
A matrix is a two-dimensional array, and Pascal's dynamic arrays express one
directly: array of array of Double is a row count plus a separate
array for each row. This article starts with a fixed 2×2 matrix, then builds a
dynamic matrix type, multiplies and transposes, solves a linear system with
Gaussian elimination and partial pivoting, computes a determinant, inverts a
matrix with Gauss-Jordan elimination, and estimates the dominant eigenvalue with
power iteration. The examples use small integer-valued matrices so that the
results can be checked by hand.
A fixed 2×2 matrix
The simplest matrix is a two-dimensional static array. Two indices address an
element: the first is the row, the second is the column. A pair of nested loops
visits every element in row-major order, and Format('%6.1f', ...)
keeps the columns aligned.
program matrix1;
{$mode objfpc}{$H+}
uses SysUtils;
var
M: array[0..1, 0..1] of Double;
I, J: Integer;
begin
M[0, 0] := 1; M[0, 1] := 2;
M[1, 0] := 3; M[1, 1] := 4;
for I := 0 to 1 do
begin
for J := 0 to 1 do
Write(Format('%6.1f', [M[I, J]]));
WriteLn;
end;
end.
The four assignments fill the matrix in the usual reading order: 1 and 2 in the first row, 3 and 4 in the second. A static array has a fixed shape that the compiler knows, so no allocation is needed. Most numerical code needs a size that is chosen at run time, which is why the rest of the article uses dynamic arrays.
$ fpc -gl matrix1.pas $ ./matrix1 1.0 2.0 3.0 4.0
Matrices as dynamic arrays
TMatrix = array of array of Double is a dynamic array whose
elements are themselves dynamic arrays. SetLength(M, Rows, Cols)
allocates both levels, and M[I][J] addresses one element.
Length(M) is the row count and Length(M[0]) the
column count of the first row. Because the rows are separate arrays, a matrix
can be ragged, but the routines here assume a rectangular shape.
program matrix2;
{$mode objfpc}{$H+}
uses SysUtils;
type
TMatrix = array of array of Double;
function MakeMatrix(Rows, Cols: Integer): TMatrix;
var
I, J: Integer;
begin
Result := nil;
SetLength(Result, Rows, Cols);
for I := 0 to Rows - 1 do
for J := 0 to Cols - 1 do
Result[I][J] := 0;
end;
procedure Fill(var M: TMatrix; const Values: array of Double);
var
I, J, K: Integer;
begin
K := 0;
for I := 0 to High(M) do
for J := 0 to High(M[I]) do
begin
M[I][J] := Values[K];
Inc(K);
end;
end;
procedure PrintMatrix(const Name: string; const M: TMatrix);
var
I, J: Integer;
begin
WriteLn(Name, ':');
for I := 0 to High(M) do
begin
for J := 0 to High(M[I]) do
Write(Format('%9.2f', [M[I][J]]));
WriteLn;
end;
end;
var
A: TMatrix;
begin
A := MakeMatrix(2, 3);
Fill(A, [1, 2, 3, 4, 5, 6]);
PrintMatrix('A', A);
WriteLn('rows = ', Length(A), ', cols = ', Length(A[0]));
end.
MakeMatrix allocates the rows and zeroes every element, so a new
matrix does not contain random values. Fill copies a flat list of
values into the two-dimensional shape in row-major order, which keeps the test
data readable. The explicit Result := nil before
SetLength silences a compiler warning about the managed result
variable.
$ fpc -gl matrix2.pas
$ ./matrix2
A:
1.00 2.00 3.00
4.00 5.00 6.00
rows = 2, cols = 3
Multiplying matrices
Multiply uses the row-column rule: the element at row I and column
J of the result is the dot product of row I of A and column J of B. The loops
follow the storage order, so the innermost loop walks along a row of B and a row
of the result, which is cache-friendly. The product of a 2×3 and a 3×2 matrix is
2×2.
program multiply;
{$mode objfpc}{$H+}
uses SysUtils;
type
TMatrix = array of array of Double;
function MakeMatrix(Rows, Cols: Integer): TMatrix;
var
I, J: Integer;
begin
Result := nil;
SetLength(Result, Rows, Cols);
for I := 0 to Rows - 1 do
for J := 0 to Cols - 1 do
Result[I][J] := 0;
end;
procedure Fill(var M: TMatrix; const Values: array of Double);
var
I, J, K: Integer;
begin
K := 0;
for I := 0 to High(M) do
for J := 0 to High(M[I]) do
begin
M[I][J] := Values[K];
Inc(K);
end;
end;
procedure PrintMatrix(const Name: string; const M: TMatrix);
var
I, J: Integer;
begin
WriteLn(Name, ':');
for I := 0 to High(M) do
begin
for J := 0 to High(M[I]) do
Write(Format('%9.2f', [M[I][J]]));
WriteLn;
end;
end;
function Multiply(const A, B: TMatrix): TMatrix;
var
I, J, K: Integer;
begin
Result := MakeMatrix(Length(A), Length(B[0]));
for I := 0 to High(A) do
for K := 0 to High(B) do
for J := 0 to High(B[0]) do
Result[I][J] := Result[I][J] + A[I][K] * B[K][J];
end;
var
A, B: TMatrix;
begin
A := MakeMatrix(2, 3);
Fill(A, [1, 2, 3, 4, 5, 6]);
B := MakeMatrix(3, 2);
Fill(B, [7, 8, 9, 10, 11, 12]);
PrintMatrix('A', A);
PrintMatrix('B', B);
PrintMatrix('A * B', Multiply(A, B));
end.
The first row of the product is (1·7 + 2·9 + 3·11, 1·8 + 2·10 + 3·12) =
(58, 64), and the second row is (139, 154). The inner loop accumulates into an
element that was zeroed by MakeMatrix; forgetting that
initialization would add the products to whatever the allocation left behind.
The inner dimension of A and the outer dimension of B must agree, but the code
does not check it.
$ fpc -gl multiply.pas
$ ./multiply
A:
1.00 2.00 3.00
4.00 5.00 6.00
B:
7.00 8.00
9.00 10.00
11.00 12.00
A * B:
58.00 64.00
139.00 154.00
Transposing a matrix
The transpose swaps rows and columns: element (I, J) moves to (J, I). A 2×3 matrix becomes 3×2. The result is allocated with the dimensions reversed, and the double loop copies every element to its new position.
program transpose;
{$mode objfpc}{$H+}
uses SysUtils;
type
TMatrix = array of array of Double;
function MakeMatrix(Rows, Cols: Integer): TMatrix;
var
I, J: Integer;
begin
Result := nil;
SetLength(Result, Rows, Cols);
for I := 0 to Rows - 1 do
for J := 0 to Cols - 1 do
Result[I][J] := 0;
end;
procedure Fill(var M: TMatrix; const Values: array of Double);
var
I, J, K: Integer;
begin
K := 0;
for I := 0 to High(M) do
for J := 0 to High(M[I]) do
begin
M[I][J] := Values[K];
Inc(K);
end;
end;
procedure PrintMatrix(const Name: string; const M: TMatrix);
var
I, J: Integer;
begin
WriteLn(Name, ':');
for I := 0 to High(M) do
begin
for J := 0 to High(M[I]) do
Write(Format('%9.2f', [M[I][J]]));
WriteLn;
end;
end;
function Transpose(const A: TMatrix): TMatrix;
var
I, J: Integer;
begin
Result := MakeMatrix(Length(A[0]), Length(A));
for I := 0 to High(A) do
for J := 0 to High(A[I]) do
Result[J][I] := A[I][J];
end;
var
A: TMatrix;
begin
A := MakeMatrix(2, 3);
Fill(A, [1, 2, 3, 4, 5, 6]);
PrintMatrix('A', A);
PrintMatrix('transpose(A)', Transpose(A));
end.
Transposing twice returns the original matrix. The operation is useful on its
own and also explains why the product A * B can be read as
Bᵀ * Aᵀ transposed. The code assumes a rectangular matrix, because
it uses Length(A[0]) as the column count for every row.
$ fpc -gl transpose.pas
$ ./transpose
A:
1.00 2.00 3.00
4.00 5.00 6.00
transpose(A):
1.00 4.00
2.00 5.00
3.00 6.00
Gaussian elimination
Gaussian elimination transforms the augmented matrix into upper triangular form by subtracting multiples of one row from the rows below it. Partial pivoting swaps the row with the largest absolute value in the current column into the pivot position, which avoids division by a small number and improves the numerical stability. Back substitution then computes the unknowns from the last row upward.
program gauss;
{$mode objfpc}{$H+}
uses SysUtils, Math;
type
TMatrix = array of array of Double;
TVector = array of Double;
function Solve(const A: TMatrix; const B: TVector): TVector;
var
M: TMatrix;
N, I, J, K, Pivot: Integer;
Factor, Temp: Double;
begin
Result := nil;
N := Length(A);
SetLength(M, N, N + 1);
for I := 0 to N - 1 do
begin
for J := 0 to N - 1 do
M[I][J] := A[I][J];
M[I][N] := B[I];
end;
for K := 0 to N - 2 do
begin
Pivot := K;
for I := K + 1 to N - 1 do
if Abs(M[I][K]) > Abs(M[Pivot][K]) then
Pivot := I;
if Abs(M[Pivot][K]) < 1E-12 then
raise Exception.Create('singular matrix');
if Pivot <> K then
for J := 0 to N do
begin
Temp := M[K][J];
M[K][J] := M[Pivot][J];
M[Pivot][J] := Temp;
end;
for I := K + 1 to N - 1 do
begin
Factor := M[I][K] / M[K][K];
for J := K to N do
M[I][J] := M[I][J] - Factor * M[K][J];
end;
end;
SetLength(Result, N);
for I := N - 1 downto 0 do
begin
Result[I] := M[I][N];
for J := I + 1 to N - 1 do
Result[I] := Result[I] - M[I][J] * Result[J];
Result[I] := Result[I] / M[I][I];
end;
end;
procedure PrintVector(const Name: string; const V: TVector);
var
I: Integer;
begin
Write(Name, ' = [');
for I := 0 to High(V) do
begin
if I > 0 then Write(', ');
Write(Format('%7.3f', [V[I]]));
end;
WriteLn(']');
end;
var
A: TMatrix;
B, X: TVector;
begin
SetLength(A, 3, 3);
A[0][0] := 2; A[0][1] := 1; A[0][2] := -1;
A[1][0] := -3; A[1][1] := -1; A[1][2] := 2;
A[2][0] := -2; A[2][1] := 1; A[2][2] := 2;
B := [8, -11, -3];
X := Solve(A, B);
PrintVector('x', X);
end.
The system 2x + y - z = 8,
-3x - y + 2z = -11, and
-2x + y + 2z = -3 has the exact solution
(2, 3, -1), and the program reproduces it to three decimals. The pivot search
runs before every elimination step, and a pivot smaller than 1E-12 raises an
exception instead of dividing by nearly zero. The augmented matrix is a local
copy, so the original A is not modified.
$ fpc -gl gauss.pas $ ./gauss x = [ 2.000, 3.000, -1.000]
Determinant
The determinant of a triangular matrix is the product of its diagonal entries, so the same elimination computes it: transform the matrix to triangular form, multiply the diagonal, and multiply by -1 for every row swap. A zero pivot means the matrix is singular and the determinant is zero. The example uses a matrix with determinant -306, which is small enough to verify by cofactor expansion.
program determinant;
{$mode objfpc}{$H+}
uses SysUtils, Math;
type
TMatrix = array of array of Double;
function Determinant(const A: TMatrix): Double;
var
M: TMatrix;
N, I, J, K, Pivot: Integer;
Factor, Temp, Sign: Double;
begin
N := Length(A);
SetLength(M, N, N);
for I := 0 to N - 1 do
M[I] := Copy(A[I], 0, N);
Sign := 1;
for K := 0 to N - 2 do
begin
Pivot := K;
for I := K + 1 to N - 1 do
if Abs(M[I][K]) > Abs(M[Pivot][K]) then
Pivot := I;
if Abs(M[Pivot][K]) < 1E-12 then
Exit(0);
if Pivot <> K then
begin
for J := 0 to N - 1 do
begin
Temp := M[K][J];
M[K][J] := M[Pivot][J];
M[Pivot][J] := Temp;
end;
Sign := -Sign;
end;
for I := K + 1 to N - 1 do
begin
Factor := M[I][K] / M[K][K];
for J := K to N - 1 do
M[I][J] := M[I][J] - Factor * M[K][J];
end;
end;
Result := Sign;
for I := 0 to N - 1 do
Result := Result * M[I][I];
end;
var
M: TMatrix;
begin
SetLength(M, 3, 3);
M[0][0] := 6; M[0][1] := 1; M[0][2] := 1;
M[1][0] := 4; M[1][1] := -2; M[1][2] := 5;
M[2][0] := 2; M[2][1] := 8; M[2][2] := 7;
WriteLn('determinant: ', FormatFloat('0.000', Determinant(M)));
WriteLn('first element after: ', FormatFloat('0.000', M[0][0]));
end.
The parameter is const, and the function copies the rows into a
local matrix with Copy, so the elimination works on private data
and the original stays intact. A plain assignment of a dynamic array would
share the rows, because the array is a reference type; the final output line
confirms that the original first element is still 6. The sign variable tracks
the parity of the row swaps. The result is -306.000, which matches the
cofactor calculation 6·(-2·7 - 5·8) - 1·(4·7 - 5·2) + 1·(4·8 - (-2)·2) = -306.
$ fpc -gl determinant.pas $ ./determinant determinant: -306.000 first element after: 6.000
Inverse
Gauss-Jordan elimination applies the row operations to the identity matrix at the same time as to the original matrix. When the left half has become the identity, the right half is the inverse. The augmented matrix therefore has twice as many columns. Partial pivoting is still needed, and a singular matrix raises an exception.
program inverse;
{$mode objfpc}{$H+}
uses SysUtils, Math;
type
TMatrix = array of array of Double;
function Inverse(const A: TMatrix): TMatrix;
var
Aug: TMatrix;
N, I, J, K, Pivot: Integer;
Factor, Temp: Double;
begin
Result := nil;
N := Length(A);
SetLength(Aug, N, 2 * N);
for I := 0 to N - 1 do
begin
for J := 0 to N - 1 do
Aug[I][J] := A[I][J];
for J := N to 2 * N - 1 do
Aug[I][J] := 0;
Aug[I][N + I] := 1;
end;
for K := 0 to N - 1 do
begin
Pivot := K;
for I := K + 1 to N - 1 do
if Abs(Aug[I][K]) > Abs(Aug[Pivot][K]) then
Pivot := I;
if Abs(Aug[Pivot][K]) < 1E-12 then
raise Exception.Create('matrix is singular');
if Pivot <> K then
for J := 0 to 2 * N - 1 do
begin
Temp := Aug[K][J];
Aug[K][J] := Aug[Pivot][J];
Aug[Pivot][J] := Temp;
end;
Factor := Aug[K][K];
for J := 0 to 2 * N - 1 do
Aug[K][J] := Aug[K][J] / Factor;
for I := 0 to N - 1 do
if I <> K then
begin
Factor := Aug[I][K];
for J := 0 to 2 * N - 1 do
Aug[I][J] := Aug[I][J] - Factor * Aug[K][J];
end;
end;
SetLength(Result, N, N);
for I := 0 to N - 1 do
for J := 0 to N - 1 do
Result[I][J] := Aug[I][N + J];
end;
procedure PrintMatrix(const Name: string; const M: TMatrix);
var
I, J: Integer;
begin
WriteLn(Name, ':');
for I := 0 to High(M) do
begin
for J := 0 to High(M[I]) do
Write(Format('%9.3f', [M[I][J]]));
WriteLn;
end;
end;
var
A, B: TMatrix;
begin
SetLength(A, 2, 2);
A[0][0] := 4; A[0][1] := 7;
A[1][0] := 2; A[1][1] := 6;
PrintMatrix('A', A);
B := Inverse(A);
PrintMatrix('inverse', B);
end.
The inverse of [[4, 7], [2, 6]] is [[0.6, -0.7], [-0.2, 0.4]], because the determinant is 10 and the adjugate is [[6, -7], [-2, 4]]. Multiplying the matrix by its inverse gives the identity to within rounding. Normalizing the pivot row before eliminating the other rows is what turns the left half into the identity; the same operation is applied to the right half in the same loop.
$ fpc -gl inverse.pas
$ ./inverse
A:
4.000 7.000
2.000 6.000
inverse:
0.600 -0.700
-0.200 0.400
Power iteration
Power iteration finds the eigenvalue of largest absolute value and its eigenvector. It starts with an arbitrary vector, repeatedly multiplies it by the matrix, and normalizes the result to unit length. The component along the dominant eigenvector grows faster than the others, so the direction converges to that eigenvector and the Rayleigh quotient converges to the eigenvalue.
program power;
{$mode objfpc}{$H+}
uses SysUtils, Math;
type
TMatrix = array of array of Double;
TVector = array of Double;
function DominantEigenvalue(const A: TMatrix; Iterations: Integer;
out V: TVector): Double;
var
N, I, J, K: Integer;
W: TVector;
Norm, Sum: Double;
begin
N := Length(A);
SetLength(V, N);
for I := 0 to N - 1 do
V[I] := 1;
for K := 1 to Iterations do
begin
SetLength(W, N);
for I := 0 to N - 1 do
begin
W[I] := 0;
for J := 0 to N - 1 do
W[I] := W[I] + A[I][J] * V[J];
end;
Norm := 0;
for I := 0 to N - 1 do
Norm := Norm + W[I] * W[I];
Norm := Sqrt(Norm);
for I := 0 to N - 1 do
V[I] := W[I] / Norm;
end;
Sum := 0;
for I := 0 to N - 1 do
for J := 0 to N - 1 do
Sum := Sum + V[I] * A[I][J] * V[J];
Result := Sum;
end;
var
A: TMatrix;
V: TVector;
Lambda: Double;
begin
SetLength(A, 3, 3);
A[0][0] := 4; A[0][1] := 1; A[0][2] := 0;
A[1][0] := 2; A[1][1] := 3; A[1][2] := 0;
A[2][0] := 0; A[2][1] := 0; A[2][2] := 1;
Lambda := DominantEigenvalue(A, 100, V);
WriteLn('eigenvalue: ', FormatFloat('0.000000', Lambda));
WriteLn('vector: [', FormatFloat('0.000000', V[0]), ', ',
FormatFloat('0.000000', V[1]), ', ',
FormatFloat('0.000000', V[2]), ']');
end.
The block matrix has eigenvalues 5, 2, and 1; the dominant one is 5, with eigenvector (1, 1, 0). The normalized vector is (0.707107, 0.707107, 0), and the Rayleigh quotient is 5.000000. The third component is present at the start but shrinks relative to the first two, because its eigenvalue 1 grows more slowly than 5. Power iteration converges slowly when the two largest eigenvalues are close in magnitude, and it fails when the dominant eigenvalue is complex.
$ fpc -gl power.pas $ ./power eigenvalue: 5.000000 vector: [0.707107, 0.707107, 0.000000]
Next steps
The dynamic arrays article explains the
two-level allocation behind TMatrix, and the
floating-point article explains the
tolerances used for pivots and comparisons. The
numerical integration article uses
similar elimination-free iteration, and the
scientific simulations article
applies matrix-like updates to grids.
Source
Gaussian elimination on Wikipedia
Free Pascal Reference guide: array types
In this article we stored a fixed matrix, built dynamic matrices, multiplied and transposed them, solved a system with partial pivoting, computed a determinant, inverted a matrix with Gauss-Jordan elimination, and estimated a dominant eigenvalue. The series continues with scientific simulations in Pascal.
Author
List all Pascal tutorials.