In: Computer Science
MATLAB code for the Gaussian elimination with partial pivoting and backward substitution to find the roots are provided below, please comment if any doubts:
Code:
%set the value of A anf b
A = [1 1 -2; 2 -3 1; 3 1 4]
B = [1; -8; 7]
%%Call the function
Guass_partial_back(A,B)
%%The function to peform the guassian eliminatio
%by partial pivoting and back substitution
function [myroots,nrow,AugmentedMat]=
Guass_partial_back(A,b);
%create the augmented matrix
augMat=[A b];
%find the rank of the matrx
ra=rank(A);
%create a row vector of size rank
for itr=1:ra
nrow(itr)=itr;
end
%fibnd the transverse
nrow=nrow';
for i=1:ra-1;
largest=0;
numIndx=0;
%find maximum in a row and return it
for k=i:ra
if
abs(augMat(nrow(k),i))>largest
largest=abs(augMat(nrow(k),i));
numIndx=k;
end
end
%row exchange procedure
if nrow(i)~=nrow(numIndx)
tempRow=nrow(i);
nrow(i)=nrow(numIndx);
nrow(numIndx)=tempRow;
end
%perform the Gaussian elimination
for itr=(i+1):ra
n(nrow(itr),i)=augMat(nrow(itr),i)/augMat(nrow(i),i);
for k=i:ra+1
augMat(nrow(itr),k)=augMat(nrow(itr),k)-n(nrow(itr),i)*augMat(nrow(i),k);
end
end
end
%the backward subsitution to find the roots
x(ra)=0;
x=x';
x(ra)=augMat(nrow(ra),ra+1)/augMat(nrow(ra),ra);
itr=ra-1;
%find all x values
while itr>0
x(itr)=(augMat(nrow(itr),ra+1)-augMat(nrow(itr),itr+1:ra)*x(itr+1:ra))/(augMat(nrow(itr),itr));
itr=itr-1;
end
%return the solution
myroots=x;
%augmented matrix
AugmentedMat=augMat;
end
Output: