这是另一种矩阵求逆的方法,其基本思想是若对A矩阵求逆,则在其右边附加一个同型的单位矩阵,然后对这个合并了的矩阵进行初等行变换至行最简形,此时再分割这个矩阵,矩阵左边的应该是一个单位矩阵,而右边的则是一就是原来A矩阵的逆。下面是相关的Lua代码,与以前代码相同的部分省略。
-
-- Merge matrices horizontally
-
MatrixMeta.merge=function(this,other)
-
if this.row~=other.row or this.column ~= other.column then
-
return nil
-
end
-
-
local data={}
-
for i=1,this.row do
-
for j=1,this.column do
-
table.insert(data,this:at(i,j))
-
end
-
-
for j=1,this.column do
-
table.insert(data,other:at(i,j))
-
end
-
end
-
-
return Matrix(data,this.row,this.row*2)
-
end
-
-
-- Divide the matrix into two parts
-
MatrixMeta.divide=function(this)
-
if this.column~=2*this.row then
-
return nil
-
end
-
-
local a={}
-
local b={}
-
local remainder
-
for i,v in ipairs(this.data) do
-
remainder=i%this.column
-
if remainder~=0 and remainder <= this.column/2 then
-
table.insert(a,v)
-
else
-
table.insert(b,v)
-
end
-
end
-
-
a=Matrix(a,this.row,this.row)
-
b=Matrix(b,this.row,this.row)
-
return a,b
-
end
-
-
-- Another way to get inversed matrix
-
MatrixMeta.inverse2=function(this)
-
if this.row ~= this.column or Determinant(this.data):eval()==0 then
-
return nil
-
end
-
-
local e={}
-
for i=1,this.row-1 do
-
table.insert(e,1)
-
for j=1,this.row do
-
table.insert(e,0)
-
end
-
end
-
table.insert(e,1)
-
-
e=Matrix(e,this.row,this.column)
-
local merged=this:merge(e)
-
merged:reduce()
-
local a,b=merged:divide()
-
return b
-
end
-
-
-