%LU分解,Doolittle分解%L为单位下三角阵,U为上三角阵clear;clc;A=[3 -5 6 4 -2 -3 8; 1 1 -9 15 1 -9 2; 2 -1 7 5 -1 6 11; -1 1 3 2 7 -
%LU分解,Doolittle分解
%L为单位下三角阵,U为上三角阵
clear;clc;
A=[3 -5 6 4 -2 -3 8;
1 1 -9 15 1 -9 2;
2 -1 7 5 -1 6 11;
-1 1 3 2 7 -1 -2;
4 3 1 -7 2 1 1;
2 9 -8 11 -1 -4 -1;
7 2 -1 2 7 -1 9];%系数矩阵
b=[11 2 29 9 5 8 25]';%n维向量
% A=[4,-2,0,4;-2,2,-3,1;0,-3,13,-7;4,1,-7,23];
% b=[1 2 3 4];
n=length(b);%方程个数n
x=zeros(n,1);%未知向量
A(2:n,1)=A(2:n,1)./A(1,1);
for i=2:n-1
A(i,i)=A(i,i)-sum(A(i,1:i-1)'.*A(1:i-1,i));
for j=i+1:n
A(i,j)=A(i,j)-sum(A(i,1:i-1)'.*A(1:i-1,j));
A(j,i)=(A(j,i)-sum(A(j,1:i-1)'.*A(1:i-1,i)))/A(i,i);
end
end
A(n,n)=A(n,n)-sum(A(n,1:n-1)'.*A(1:n-1,n));
A
U=A;L=A;
for i=1:n
L(i,i)=1;
end
for i=1:n-1
for j=i+1:n
L(i,j)=0;
end
end
L %下三角阵
for i=2:n
for j=1:i-1
U(i,j)=0;
end
end
U %上三角阵
%-----用LU分解解线性方程组------
y=zeros(n,1);
y(1)=b(1);
for i=2:n
y(i)=b(i)-sum(L(i,1:i-1)'.*y(1:i-1));
end
y
x(n)=y(n)/U(n,n);
for i=n-1:-1:1
x(i)=(y(i)-sum(U(i,i+1:n)'.*x(i+1)))/U(i,i);
end
x
%可不必先将A分解后再求解Ly=b,计算y与A的分解可同时进行
%对增广矩阵A=[A,b]进行LU分解,分解后第n+1列位置上的元即是y
,