矩阵的LU分解(带选主元)求解线性方程组的matlab代码实现

function X=lufact(A,B)
%Input -A is a N*N matrix
%      -B is a N*1 matrix
%output X is a n*1 matrix containing the solution to AX=B
[N,N]=size(A);
X=zeros(N,1);
Y=zeros(N,1);
R=1:N;%reserve the row permutation infomation
C=zeros(1,N);%the temporary storage matrix
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(p+j-1,:);
A(p+j-1,:)=C;
d=R(p);
R(p)=R(p+j-1);
R(p+j-1)=d;
if A(p,p)==0
   fprintf("A is singular,No unique solution");
   break;    
end
%Let A break into upper triangular matrix and lower triangular
for k=p+1:N
    m=A(k,p)/A(p,p);
    A(k,p)=m;
    A(k,p+1:N)=A(k,p+1:N)-m*A(p,p+1:N);
      
end
%caculate matrix Y
Y(1)=B(R(1));
for i=2:N
    Y(i)=B(R(i))-A(i,1:i-1)*Y(1:i-1);
end
%caculate matrix X
X(N)=Y(N)/A(N,N);
for j=N-1:-1:1
    X(j)=(Y(N)-A(j,j+1:N)*X(j+1:N))/A(j,j); 
end
 
end
end

测试:
A=[1 3 5 7;2 -1 3 5;0 0 2 5;-2 -6 -3 1];
B=[1 2 3 4]’;
求解的结果如下:
X=lufact(A,B)
X =
2.0571
1.3592
-3.4898
1.8000

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值