Matlab實現——求矩陣的逆(LU分解)

來源:互聯網
上載者:User

 

Program  (Solve By Factorization with Pivoting )

思路及原理:

就得到:

程式:

function  X=Ni(A)%Input  - A is an N x N matrix%Output - I is an N x N inverse matrix of A %and I(j,:)containing the solution to AX(:,j) =E(:,j).%Initialize X, Y,the temporary storage matrix C, and the row % permutation information matrix R[N,N]=size(A);B=eye(N);   %B is an N x N identity matrixX=zeros(N,N);Y=zeros(N,N);C=zeros(1,N);R=1:N;%the next steps is to find the factorization(factorize for only once)for p=1:N-1%Find the pivot row for column p   [max1, j]=max(abs(A(p:N,p)));%Interchange row p and j      C=A(p,:);      A(p,:)=A(j+p-1,:);      A(j+p-1,:)=C;      d=R(p);      R(p)=R(j+p-1);      R(j+p-1)=d;      if A(p,p)==0      'A is singular.  No unique solution'      break      end   %Calculate multiplier and place in subdiagonal portion of A      for k=p+1:N         mult=A(k,p)/A(p,p);     A(k,p) = mult;         A(k,p+1:N)=A(k,p+1:N)-mult*A(p,p+1:N);      endendfor j=1:N        %when j is fixed then the method is similar to the Program 3.3    %Solve for Y(:,j)    Y(1,j) = B(R(1),j);    for k=2:N        Y(k,j)= B(R(k),j)-A(k,1:k-1)*Y(1:k-1,j);    end    %Solve for X(:,j)    X(N,j)=Y(N,j)/A(N,N);    for k=N-1:-1:1        X(k,j)=(Y(k,j)-A(k,k+1:N)*X(k+1:N,j))/A(k,k);    endend

 

如果運行程式可以看到:Ni(A)和inv(A)運算得到的逆矩陣是相同的

而且 A*Ni(A)=E 所以結果是令人滿意的

此方法中LU非直接三角分解只用了一次,通過增加一個j的迴圈,實現方程組的逐個求解,將得到的N個解向量C(:,j)合到X中得到最終結果。

個人感覺此方法的穩定性不錯,暫時不需要改進了吧。

設計這個程式的時候並沒遇到什麼困難,思路已經想好了:

求解N個方程AXj=Ej;只要通過兩個矩陣的對應列向量來儲存Xj和Ej以及增加一個j迴圈,然後利用原來的Program就能達到預期的目的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.