Welcome to the World of Modelling and Simulation

What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ...

Application of Gaussian Elimination to Solve System of Linear Algebraic Equations

Problem: In this example, we are going to solve the following system of linear algebraic equations by the widely-used Gaussian elimination method. Here, we are going to develop a MATLAB program that implements the Gaussian elimination to solve the following linear algebraic equations.

System of Linear Algebraic Equations








The following program implements Gaussian elimination method with partial pivoting and scaling to solve system of linear algebraic equations. The explanations of the codes are mentioned just right of each line.

MATLAB Program for Gauss Elimination Method

% Gaussian elimination with partial pivoting and scaling
 
function x = gausselimination(a,b)
 
% a - (nxn) matrix
% b - column vector of length n
 
format long;
 
m=size(a,1); % get number of rows in matrix a
 
n=length(b); % get length of b
 
if (m ~= n)
    
    error('a and b do not have the same number of rows')
    
end
 
a(:,n+1)=b;  % Forming (n,n+1) augmented matrix
 
for c=1:n
              
for r=c:m
     
% Scaling of the input matrix "a"
       
    Z(r,c) = a(r,c)/max(a(r,c:n));  % Scaling prior to pivoting 
 
    K(r:r,c:c)=Z(r,c); % Normalized coefficient parameters saved temporality 
                       % to another matrix "K"     
end
 
disp(K);
           
[~,f]=max(abs(K(1:r,c:c))); % Finding maximum absolute value from "K" matrix 
                            % for switching rows in matrix "a"      
disp(f);  
 
a([c,f],1:n+1)=a([f,c],1:n+1); % Switching between two rows 
                                                                                    
disp(a);
                                        
for i=c

% Making diagonal element of matrix "a" into 1.0
    
    a(i,i:n+1) = a(i,i:n+1)/a(i,i);   
 
for j=i+1:n
    
    % Making all elements below the diagonal element into zero
 
    a(j,i:n+1) = a(j,i:n+1) - a(j,i)*a(i,i:n+1);
    
end
 
end
 
disp(a);
 
end
 
% Process of back substitution
 
for j=n-1:-1:1
 
    a(j,n+1) = a(j,n+1) - a(j,j+1:n)*a(j+1:n,n+1);
 
end
    
% Returning solution
 
x=a(:,n+1);
 
end


Program Outputs:

ans =
 
  -1.761817043997860
   0.896228033874012
   4.051931404116157
  -1.617130802539541
   2.041913538501913
   0.151832487155935

Therefore, the solutions of the six linear algebraic equations are -1.76; 0.89; 4.05; -1.62; 2.04 and 0.15.

No comments:

Post a Comment