I've made a library for Delphi to work with matrices.
Everything in the library works perfectly as intended save the Matrix Inversion Procedure.
I've used the Gauss-Jordan method of Matrix Inversion & everything works excellent for square matrices upto 7x7.
From 8x8 onwards, I get a 'Invalid Floating Point' Error in this line :
tCopy.Matrix[i,j] := tCopy.Matrix[i,j] / tmp;
in the
try .. except block.
I've tried to debug this, but I cant seem to find the reason of it.
If you guys need to the entire library, I'll provide it.
I hope to get some help on this issue.
Best Regards
KKR
type
TMatrix = record
Row : Integer;
Col : Integer;
Matrix : Array OF Array OF Extended;
End;
Procedure MatrixInverse(TargetMatrix : TMatrix; var Inverse : TMatrix; var Singular : Boolean);
var
IdentityMatrix, tCopy : TMatrix;
i, j, k : integer;
tmp, det : Extended;
Begin
MatrixDeterminant(TargetMatrix, det);
if (det = 0) then
Begin
Singular := True;
CreateNullMatrix(TargetMatrix.Row, TargetMatrix.Col, IdentityMatrix);
CopyMatrix(IdentityMatrix, Inverse);
exit;
End;
CopyMatrix(TargetMatrix, tCopy);
if (TargetMatrix.Row <> TargetMatrix.Col) then
Begin
Exit;
End;
InitMatrix(TargetMatrix.Row, TargetMatrix.Col, Inverse);
CreateIdentityMatrix(TargetMatrix.Row, TargetMatrix.Col, IdentityMatrix);
for i := 0 to TargetMatrix.Row - 1 do
Begin
tmp := tCopy.Matrix[i,i];
for j := 0 to TargetMatrix.Row - 1 do
Begin
try
tCopy.Matrix[i,j] := tCopy.Matrix[i,j] / tmp;
IdentityMatrix.Matrix[i,j] := (IdentityMatrix.Matrix[i,j] / tmp);
except
on E:Exception do
Begin
Singular := True;
CreateNullMatrix(TargetMatrix.Row, TargetMatrix.Col, IdentityMatrix);
CopyMatrix(IdentityMatrix, Inverse);
exit;
End;
End;
End;
for k := 0 to TargetMatrix.Row - 1 do
Begin
tmp := tCopy.Matrix[k, i];
for j := 0 to TargetMatrix.Row - 1 do
Begin
if (i = k) then
Begin
break;
End
else
Begin
tCopy.Matrix[k,j] := (tCopy.Matrix[k, j] - (tCopy.matrix[i, j] * tmp));
IdentityMatrix.Matrix[k, j] := (IdentityMatrix.Matrix[k, j] - (IdentityMatrix.Matrix[i, j] * tmp));
End;
End;
End;
End;
DestroyMatrix(tCopy);
CopyMatrix(IdentityMatrix, Inverse);
DestroyMatrix(IdentityMatrix);
Singular := False;
End;