Saturday, June 13, 2015

Matlab code for solving linear equations using Gauss elimination process

clc; clear all; close all;
% A = [1 3;2 4];
% b = [5;6];

A=[ 2 1 1; 4 -6 0; -2 7 2 ]; 

b=[ 5;-2;9 ];

[m,n] = size(A);
if m~=n, error('A matrix needs to be square'); end
nb = n+1;  Ab = [A b];   %  Augmented system
fprintf('\n Begin forward elimination with Augmented system;\n'); disp(Ab);


for i =1:n-1    
    pivot = Ab(i,i);
   
    for k=i+1:n
        factor     = - Ab(k,i)/pivot;
        Ab(k,i:nb) = Ab(k,i:nb) - (Ab(k,i)/pivot)*Ab(i,i:nb);  
        fprintf('Multiplication factor is %g\n',factor);
        disp(Ab); 
        
        pause;
    end
    fprintf('\n After elimination in column %d with pivot = %f \n\n',i,pivot);
    disp(Ab);
    pause;
end


x    = zeros(n,1);   % Initializing the x vector to zero
x(n) = Ab(n,nb) /Ab(n,n);
for i= n-1:-1:1
    x(i) = (Ab(i,nb) - Ab(i,i+1:n)*x(i+1:n))/Ab(i,i);
end
x

No comments:

Post a Comment