Matlab Code For Navie Gauss Elimination

posted on 23 Nov 2014 03:16 by unchain in Knowlage directory Knowledge

Edit window (m-file)


function x = Navie_Gauss_Elimination(A) 

% Check Number of equation and Unknown are equal or not 

if size(A,1)~=(size(A,2)-1) 

    fprintf('Number of unknow not = Number of equation , Can not find Solution') 

    pause 

    return 

end 

 



% Check Det of A , if det A = 0 , So Can't Solve    

if det(A(:,[1:size(A,2)-1])) == 0 

    fprintf('Derlivative of this system = 0 , Can not find Solution') 

    pause 

    return 

end 

 

 %Forward Elimination 

 

 for j=1:size(A,2)-2 

    for i=j:1:size(A,1)-1 

        if A(j,j)~=0 

            A(i+1,:) = A(i+1,:)-A(j,:)*(A(i+1,j)/A(j,j)) 

           % disp(j) 

           % disp(i) 

        else 

             A(i+1,:) = A(i+1,:)-A(j,:)*0; %Not good for program yet , We must switch row but in this example we not going to do that yet. 

        end 

    end 

 end 

 

 %Back Subtitution 

 

 b= A(:,size(A,2)); 

 br = size(b,1); 

 bc = size(b,2); 

 

 Ar = size(A,1); 

 Ac = size(A,2); 

 

 

 x(br) = b(br,bc)/A(Ar,Ac-1); 

 for k = 1:1:Ar-1 

     

     x(br-k) = (b((br-k),bc) - (A(Ar-k,[Ac-k-1:Ac-1])*x([br-k:br])') )/A(Ar-k,Ac-k-1); 

 end 

 

 x=x' 



----------------------------------------------------------------

. Test function with the below linear system.

 

 

Command window


>> A = [3,-0.1,-0.2,7.85;0.1,7,-0.3,-19.3;0.3,-0.2,10,71.4]

A =

    3.0000   -0.1000   -0.2000    7.8500

    0.1000    7.0000   -0.3000  -19.3000

    0.3000   -0.2000   10.0000   71.4000

 

>> Naive_Gauss_Elimination(A)

A =

    3.0000   -0.1000   -0.2000    7.8500

         0    7.0033   -0.2933  -19.5617

    0.3000   -0.2000   10.0000   71.4000

 

A =

    3.0000   -0.1000   -0.2000    7.8500

         0    7.0033   -0.2933  -19.5617

         0   -0.1900   10.0200   70.6150

 

 

 

 

A =

    3.0000   -0.1000   -0.2000    7.8500

         0    7.0033   -0.2933  -19.5617

         0         0   10.0120   70.0843

 

x =

    3.0000

   -2.5000

    7.0000

 

ans =

    3.0000

   -2.5000

 

    7.0000


 

Comment

Comment:

Tweet