matlab求解线性方程组(前代法,回代法,Gauss消去法,追赶法,列主元Gauss消去法)

1.前代法

l=[1.2 0 0;3.2 -1.5 0;5.3 -2.7 4.1];
b=[1.32;4.72;9.63];
for j=1:2
    b(j)=b(j)/l(j,j);
    b(j+1:3)=b(j+1:3)-b(j)*l(j+1:3,j);
end
b(3)=b(3)/l(3,3)

2.回代法

u=[3.7 7.2 6.9;0 -1.4 -5.8;0 0 2.1];
y=[4.10;0.90;-0.63];
for j=3:-1:2
    y(j)=y(j)/u(j,j);
    y(1:j-1)=y(1:j-1)-y(j)*u(1:j-1,j);
end
y(1)=y(1)/u(1,1)

3.Gauss消去法

A=[8,19,-5;-17,6,11;10,2,-3];
b=[31;28;5];
y=inv(A)*b
n=length(b);
x=zeros(n,1);
for k=1:n-1
    for i=k+1:n
        Aik=A(i,k)/A(k,k)
             for j=k:n
                 A(i,j)=A(i,j)-Aik*A(k,j);
             end
             A
             b(i)=b(i)-Aik*b(k)
    end
end
x(n)=b(n)/A(n,n)
for k=n-1:-1:1
    S=b(k);
    for j=k+1:n
        S=S-A(k,j)*x(j);
    end
    x(k)=S/A(k,k)
end
x

4.追赶法

function x=chase(a,b,c,f)
   N=length(f);
   x=zeros(1,N);
   y=zeros(1,N);
   d=zeros(1,N);
   u=zeros(1,N);
   d(1)=b(1);
   for i=1:N-1
       u(i)=c(i)/d(i);
       d(i+1)=b(i+1)-a(i+1)*u(i);
   end
   y(1)=f(1)/d(1);
   for i=2:N
       y(i)=(f(i)-a(i)*y(i-1))/d(i);
   end
   x(N)=y(N);
   for i=N-1:-1:1
       x(i)=y(i)-u(i)*x(i+1);
   end
end
a=[0,8,8,8];
b=[6,6,6,6];
c=[1,1,1,0];
f=[8,23,38,48];
x=chase(a,b,c,f)

5.列主元的Gauss消去法

function [X]=gausslie(A,b)
   [N,N]=size(A);
   X=zeros(N,1);
   C=zeros(1,N);
   B=[A b];
   for i=1:N-1
       [max1,j]=max(abs(B(i:N,i)));
       C=B(i,:);
       B(i,:)=B(j+i-1,:);
       B(j+i-1,:)=C;
       if A(i,i)==0
           disp('无解');
           break
       end
       for k=i+1:N
           temp=B(k,i)/B(i,i);
           B(k,i+1:N+1)=B(k,i+1:N+1)-temp*B(i,i+1:N+1);
       end
   end
   X(N)=B(N,N+1)/B(N,N);
   for k=N-1:-1:1
      X(k)=(B(k,N+1)-B(k,k+1:N)*X(k+1:N))/B(k,k);
   end
end
A=[12,-3,3;-18,3,-1;1,1,1];
b=[15;-15;6];
X=gausslie(A,b)

你可能感兴趣的:(matlab求解线性方程组(前代法,回代法,Gauss消去法,追赶法,列主元Gauss消去法))