首先对n * n的矩阵求逆,然后用逆矩阵*向量T,得到你要的解,这个解法只适用于n个未知数
n个方程的方程组
矩阵定义如下
TDoubleMatrix = class
private
FMatrix :array of array ofdo
uble ;
FMaxX :Integer ;
FMaxY :Integer ;
protected
procedure SetXY(X,Y :Integer) ;
public
constructor Create(X,Y:Integer) ;
destructor Destroy ;
override ;
procedure ClearMatrix ;
function SetValue(X,Y:Integer ;
const Value
ouble) :Boolean ;
function GetValue(X,Y:Integer ;
var VAlue
ouble) :Boolean ;
function AssignFrom(Source:TDoubleMatrix) :Boolean;
function swap(i1,j1,i2,j2:Integer):Boolean ;
procedure DisplayTo(sg :TStringGrid) ;
published
property X :Integer read FMaxX ;
property Y :Integer read FMaxY ;
end ;
求逆矩阵算法如下:
function InverseMatrix(InMatrix,OutMatrix:TDoubleMatrix;Dimension:Integer):Boolean ;
var
tmpMatrix :TDoubleMatrix ;
iis :array of Integer ;
jjs :array of Integer ;
i,j,k :Integer ;
fMax,f ,fDet,tmp,mkk
ouble ;
v1,v2,v3
ouble ;
begin
// 初始化
tmpMatrix := TDoubleMatrix.Create(Dimension,Dimension) ;
tmpMatrix.AssignFrom(InMatrix) ;
Setlength(iis,Dimension) ;
Setlength(jjs,Dimension) ;
f := 0 ;
fDet := 1.0 ;
for k := 0 to Dimension-1do
begin
// 第一步,全选主元
fMax := 0 ;
for i := k to Dimension-1do
begin
for j:= k to Dimension-1do
begin
tmpMatrix.GetValue(i,j,tmp) ;
f := Abs(tmp) ;
if f > fMax then
begin
fMax := f ;
iis[k] := i ;
jjs[k] := j ;
end;
end ;
end ;
if Abs(fMax) < 0.0001 then
break ;
if iis[k] <> k then
begin
f := -f ;
for i := 0 to Dimension-1do
tmpMatrix.swap(k,i,iis[k],i) ;
end ;
if jjs[k] <> k then
begin
f := -f ;
for i:=0 to Dimension-1do
tmpMatrix.swap(i,k,i,jjs[k]) ;
end ;
// 计算行列值
tmpMatrix.GetValue(k,k,mkk) ;
fDet := fDet* mkk ;
// 计算逆矩阵
// 第二步
mkk := 1/mkk ;
tmpMatrix.SetValue(k,k,mkk) ;
//第三步
for j:= 0 to Dimension-1do
if j <> k then
begin
tmpMatrix.GetValue(k,j,tmp) ;
tmp := tmp*mkk ;
tmpMatrix.SetValue(k,j,tmp) ;
end ;
//第四步
for i := 0 to Dimension-1do
begin
if i <> k then
for j := 0 to Dimension-1do
begin
if j<> k then
begin
tmpMatrix.GetValue(i,j,v1) ;
tmpMatrix.GetValue(i,k,v2) ;
tmpMatrix.GetValue(k,j,v3) ;
tmp := v1-v2*v3 ;
tmpMatrix.SetValue(i,j,tmp) ;
end ;
end ;
end ;
//第五步
for i:= 0 to Dimension-1do
if i<>k then
begin
tmpMatrix.GetValue(i,k,tmp) ;
tmp := tmp*(-mkk) ;
tmpMatrix.SetValue(i,k,tmp) ;
end;
end ;
for k:=Dimension-1do
wnto 0do
begin
if jjs[k]<>k then
begin
for i := 0 to Dimension-1do
tmpMatrix.Swap(k,i,jjs[k],i) ;
end ;
if iis[k] <> k then
begin
for i := 0 to Dimension-1do
tmpMatrix.Swap(i,k,i,iis[k]) ;
end ;
end ;
Result := outMatrix.AssignFrom(tmpMatrix) ;
// 清除
Setlength(iis,0) ;
SetLength(jjs,0) ;
tmpMatrix.Free ;
end ;