function x=GaussianElimination(A,b) %高斯消元
%inputs A:系数矩阵n×n维方阵;b:n×1维矩阵
%outputs x的n个解或不存在唯一解
[n,m]=size(A);
if n~=m
error('A must be square');
end
if n~=size(b)
error('The size of b must be equal to the number of rows of A');
end
Aug=[A,b];
for i=1:n-1 %step1
p=i;
while p<=n && Aug(p,i)==0
p=p+1;
end
if p>n %若n行中不存在非零元,无唯一解
error('no unique solution exist');
end
if p~=i
Aug([i,p],:)=Aug([p,i],:); %step3 换行
end
for j=i+1:n
m(j,i)=Aug(j,i)/Aug(i,i);
Aug(j,i:n+1)=Aug(j,i:n+1)-m(j,i)* Aug(i,i:n+1);
end
end
if Aug(n,n)==0
error('no unique solution exist');
end
x=zeros(n,1);
x(n)=Aug(n,n+1)/Aug(n,n);
for i=n-1:-1:1
s=Aug(i,i+1:n)*x(i+1:n);
x(i)=(Aug(i,n+1)-s)/Aug(i,i);
end
disp(x);
end
高斯消元Gaussian Elimination with Backward Substitution
于 2023-12-01 14:27:59 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)