用gauss消去法解线性方程组(数值数学实验教程P74ex5.2)
function [x,Ak] =caguss_elimination(A,b,epsilon)
%gauss消去法解线性方程组
%A-系数矩阵;b-右端向量
%输出Ak(:,:,k)三维数值,它的第k页保存消元过程中的第k次消元后得到的增广矩阵
[m,n]=size(A);
A=[A,b];
Ak=zeros(m,n+1,n-1);
for k=1:n-1
if abs(A(k,k))<=epsilon
str=[‘第’,num2str(k),‘步消元主元素太小!’];
error(str);
else
%求消元因子
A(k+1:n,k)=A(k+1:n,k)/A(k,k);
%进行消元步
A(k+1:n,k+1:n+1)=A(k+1:n,k+1:n+1)-A(k+1:n,k)*A(k,k+1:n+1);
end
Ak(:,:,k)=A;
end
%回代过程
A(n,n+1)=A(n,n+1)/A(n,n);
for k=n-1: -1:1
A(k,n+1)=(A(k,n+1)-A(k,k+1:n)*A(k+1:n,n+1))/A(k,k);
end
x=A(:,n+1);
end
for i=10:10:100
A=diag(repmat([-4], 1, i))+diag(repmat([1], 1, i-1), 1)+diag(repmat([1], 1, i-1), -1);
A(i,i)=4;
b=zeros(i,1);
b(1,1)=-3;
b(i,1)=-3;
for j=2:i-1
b(j,1)=-2;
end
epsilon=1e-10;
[x,Ak] =caguss_elimination(A,b,epsilon);
x
end