线性代数学习六,通过初等行变换对矩阵求逆

  这是另一种矩阵求逆的方法,其基本思想是若对A矩阵求逆,则在其右边附加一个同型的单位矩阵,然后对这个合并了的矩阵进行初等行变换至行最简形,此时再分割这个矩阵,矩阵左边的应该是一个单位矩阵,而右边的则是一就是原来A矩阵的逆。下面是相关的Lua代码,与以前代码相同的部分省略。

  1. -- Merge matrices horizontally
  2. MatrixMeta.merge=function(this,other)
  3.         if this.row~=other.row or this.column ~= other.column then
  4.                 return nil
  5.         end
  6.  
  7.         local data={}
  8.         for i=1,this.row do
  9.                 for j=1,this.column do
  10.                         table.insert(data,this:at(i,j))
  11.                 end
  12.  
  13.                 for j=1,this.column do
  14.                         table.insert(data,other:at(i,j))
  15.                 end
  16.         end
  17.  
  18.         return Matrix(data,this.row,this.row*2)
  19. end
  20.  
  21. -- Divide the matrix into two parts
  22. MatrixMeta.divide=function(this)
  23.         if this.column~=2*this.row then
  24.                 return nil
  25.         end
  26.  
  27.         local a={}
  28.         local b={}
  29.         local remainder
  30.         for i,v in ipairs(this.data) do
  31.                 remainder=i%this.column
  32.                 if remainder~=0 and remainder <= this.column/2 then
  33.                         table.insert(a,v)
  34.                 else
  35.                         table.insert(b,v)
  36.                 end
  37.         end
  38.        
  39.         a=Matrix(a,this.row,this.row)
  40.         b=Matrix(b,this.row,this.row)
  41.         return a,b
  42. end
  43.  
  44. -- Another way to get inversed matrix
  45. MatrixMeta.inverse2=function(this)
  46.         if this.row ~= this.column or Determinant(this.data):eval()==0 then
  47.                 return nil
  48.         end
  49.  
  50.         local e={}
  51.         for i=1,this.row-1 do      
  52.                 table.insert(e,1)              
  53.                 for j=1,this.row do
  54.                         table.insert(e,0)
  55.                 end
  56.         end
  57.         table.insert(e,1)
  58.        
  59.         e=Matrix(e,this.row,this.column)       
  60.         local merged=this:merge(e)
  61.         merged:reduce()
  62.         local a,b=merged:divide()
  63.         return b
  64. end
  65.  
  66.  
  67.  

Algorithm Comments(0) 2008年8月27日 12:18