数值分析算法 MATLAB 实践 线性方程组 Gauss消去法
Gauss消去法
function solution =Gauss(A,b)
n = length(b);
for k=1:n-1
for i=k+1:n
mik=A(i,k)/A(k,k);
for j=k+1:n
A(i,j)=A(i,j)-mik*A(k,j);
end
b(i)=b(i)-mik*b(k);
end
end
solution(n)=b(n)/A(n,n);
for i=n-1:-1:1
for j=i+1:n
solution(i)=solution(i)+A(i,j)*solution(j);
end
solution(i)=(b(i)-solution(i))/A(i,i);
end
end
function solution=GaussFunmethod(gauss, Presion)
if nargin==2
try
digits(Precision);
cath
disp('你输入的精度有误');
digits(10);
end
else
digits(10);
end
Ab=vpa(gauss)
row=size(Ab,1);
col=size(Ab,2);
if ndims(Ab)~=2|(col-row)~=1
disp('矩阵的大小有误');
return
end
if det(gauss(:,1:row))==0
disp('该方程的系数矩阵行列式为零');
return
end
for i=1:row
j=i;
while Ab(j,i)==0
j=j+1;
end
temp=Ab(i,:);
Ab(i,:)=Ab(j,:);
Ab(j,:)=temp;
for k=i+1:row
Ab(k,:)=vpa(Ab(k,:)-Ab(i,:)*Ab(k,i)/Ab(i,i));
end
end
for i=row:-1:1
temp=Ab(i,col);
for k=i+1:row
temp=vpa(temp-solution(k)*Ab(i,k));
end
solution(i)=vpa(temp/Ab(i,i));
end
end
Gauss主元素消去法
function X=Gauss_Mainmethod(A,b)
zengguang=[A b];
Ab = [A,b]
n=length(b);
ra=rank(A);
rz=rank(zengguang);
temp1=rz-ra;
if temp1>0
disp('方程组无一般意义下的解,系数矩阵与增广矩阵秩不同.')
return
end
if (ra==rz)
if (ra==n)
X=zeros(n,1); C=zeros(1,n+1);
for p= 1:n-1
[Y,j]=max(abs(zengguang(p:n,p))); C=zengguang(p,:);
zengguang(p,:)= zengguang(j+p-1,:); zengguang(j+p-1,:)=C;
for k=p+1:n
m= zengguang(k,p)/ zengguang(p,p);
zengguang(k,p:n+1)= zengguang(k,p:n+1)-m* zengguang(p,p:n+1);
end
end
b=zengguang(1:n,n+1);A=zengguang(1:n,1:n); X(n)=b(n)/A(n,n);
for q=n-1:-1:1
X(q)=(b(q)-sum(A(q,q+1:n)*X(q+1:n)))/A(q,q);
end
else
disp('方程组为欠定方程组')
end
X = X';
end
function x=principal_element(A,b)
[rows,~]=size(A);
aug_mat=[A,b];Ab= [A,b]
for i=1:rows
temp_list=aug_mat(:,i);
temp_list(1:max(1,i-1))=0;
[~,exchange_pos]=max(abs(temp_list));
aug_mat([i,exchange_pos],:)=aug_mat([exchange_pos,i],:);
coefficient=aug_mat(:,i);
coefficient=-coefficient./coefficient(i);
coefficient(i)=0;
aug_mat=coefficient*aug_mat(i,:)+aug_mat;
end
divisor=aug_mat((1:rows)+(0:rows:(rows*(rows-1))))';
aug_mat=aug_mat./divisor;
x=aug_mat(:,rows+1:end);
x =x';
end
Gauss-Jordan消去法
function x = GaussJordan(A, b)
%function x = GaussJordan(A, b)
%GaussJordan消去法
%A为方程组的系数矩阵 b为方程组的右端项;
n = length(b);
if size(A, 1) ~= n || size(A, 2) ~= n
error('Matrix-vector size mismatch.');
end
Ab = [A, b]
% Perform Gauss-Jordan elimination
% augmented matrix
A = [A, b];
for k = 1 : n
A(k, :) = A(k, :) / A(k, k);
for i = k + 1 : n
m = A(i, k) / A(k, k);
A(i, :) = A(i, :) - m * A(k, :);
end
end
for k = n : -1 : 1
for i = k - 1 : -1 : 1
m = A(i, k) / A(k, k);
A(i, :) = A(i, :) - m * A(k, :);
end
end
x = A(:, n + 1);
x =x';
end