-
Notifications
You must be signed in to change notification settings - Fork 0
/
gausselimination.m
52 lines (48 loc) · 1.34 KB
/
gausselimination.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function [soln] = gausselimination( mat1,values,size )
%this function uses the direct method-gaussian elimination to solve a set
%of linear algebraic equations when a matrix is input
soln=zeros(size,1);
beta=values;
for i=1:size
if i==1 %for the first row of matrix (special case)
e=mat1(1,1);
for j=1:size
mat1(i,j)=mat1(i,j)/e; %dividing the entire row elements by first element
end
beta(1)=beta(1)/e;
for k=i+1:size
c=mat1(k,1);
for j=1:size
mat1(k,j)=mat1(k,j)-c*mat1(1,j); %subtracting the elements of the next rows of the first column from the first element
end
beta(k)=beta(k)-c*beta(1);
end
elseif i~=size %for any other row
f=mat1(i,i);
for j=1:size
mat1(i,j)=mat1(i,j)/f;
end
beta(i)=beta(i)/f;
for k=i+1:size
d=mat1(k,i);
for j=1:size
mat1(k,j)=mat1(k,j)-d*mat1(i,j);
end
beta(k)=beta(k)-d*beta(i);
end
else
beta(i)=beta(i)/mat1(i,i);
mat1(i,i)=1;
end
end
for m=size:-1:1
if m==size
soln(size)=beta(size);
else
sum=0.0;
for g=m+1:size
sum=sum+mat1(m,g)*soln(g);
end
soln(m)=(beta(m,1)-sum)/mat1(m,m); %calculating the solution by backward sweeping
end
end