Matlab Code : Gauss Elimination With Partial Pivoting

posted on 25 Nov 2014 22:02 by unchain in Knowlage directory Knowledge

Edit window (m-file)

function x = Gauss_Elimination_With_Partial_Pivoting(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 

 

 

 

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

 %Check for largest C in row for make pivot row.(Switch Row) 

     

     MaxC = max(abs(A([j:size(A,1)],j))); 

     Maxrowpos = find(MaxC == abs(A([j:size(A)],j)))+j-1; 

     Maxrow = A(Maxrowpos,:); 

     if MaxC ~= A(j,j) %If original Piviot row have max C , Then go Forward Eliminate No need to switch row 

         A(Maxrowpos,:)=[]; 

        if j == 1 && Maxrowpos ~= 1 

         A=[Maxrow;A]

        elseif j==2

         A=[A(1,:);Maxrow;A([2:size(A)],:)]

        else

         A=[A([1:j-1],:);Maxrow;A([j:size(A)],:)]

        end

     end

   

    

 %Forward Elimination

    

    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;

        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'

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

Solve for unknowns in the linear algebraic system based on the Gauss elimination method with Partial pivoting. 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

 

>> Gauss_Elimination_With_Partial_Pivoting(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