用matlab编写函数,输入为线性方程组系数矩阵A,常数项b,输出为排列阵P,单位下三角矩阵L,上三角矩阵U,方程组的解x
具体算法参照施吉林的《计算机数值方法》第三版
function [P,L,U,x] = my_doolittle(A,b)
m=length(A);
P = eye(m);
L = eye(m);
%当r=1时,单独求解
a = [A b];
[num,idx] = max(A(:,1));
a = exchange_row(a,1,idx); %为了换行方便,调用一个自己构造的换行函数
P = exchange_row(P,1,idx);
a(2:m,1) = a(2:m,1)/a(1,1);
%当r=2:m-1时,依照算法逐层运算
for j=2:m-1
for i=j:m
a(i,j) = a(i,j)-a(i,1:j-1)*a(1:j-1,j);
end
n_max = a(j,j);
for i=j+1:m
if a(i,j)>n_max
idx = i;
n_max = a(i,j);
end
end
a = exchange_row(a,j,idx);
P = exchange_row(P,j,idx);
a(j+1:m,j) = a(j+1:m,j)/a(j,j);
for col = j+1:m+1
a(j,col) = a(j,col)-a(j,1:j-1)*a(1:j-1,col);
end
end
%单独求解增广矩阵最后一行倒数两个元素
a(m,m) = a(m,m)-a(m,1:m-1)*a(1:m-1,m);
a(m,m+1) = a(m,m+1)-a(m,1:m-1)*a(1:m-1,m+1);
for i=2:m
for j=1:i-1
L(i,j) = a(i,j);
end
end
U = a(:,1:end-1);
for i=2:m
for j=1:i-1
U(i,j) = 0;
end
end
y = a(:,end);
x(m,1) = y(m,1)/U(m,m);
%利用Ux=y的算法求解x
for i=m-1:-1:1
x(i,1)=(y(i,1)-U(i,i+1:m)*x(i+1:m,1))/U(i,i);
end
end
%输入矩阵a,要交换的行数i和j,对a矩阵进行行交换
function a = exchange_row(a,i,j)
temp = a(i,:);
a(i,:) = a(j,:);
a(j,:) = temp;
end