-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgauss.m
51 lines (51 loc) · 1.39 KB
/
gauss.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
function sol = gauss(A)
% A-> augmented matrix, i.e. A=[M|N] where Mx=N
% sample input : gauss([2 1 -1 8;-3 -1 2 -11;-2 1 2 -3])
% sample output:
% 2.0000
% 3.0000
% -1.0000
[r,c]=size(A);
% sin -> whether the matrix is singular(sin=1) or non-singular(sin=0)
singular=false;
for i=1:r
% finding the i-th pivot:
% partial pivoting:
if(i<r)% do partial pivoting only if there are any row below the current row
imax=i; %index of the element with maximum value
max=A(i,i); %value of that element
for k=i+1:r
% finding the max
if abs(A(k,i))>abs(max)
max=A(k,i);
imax=k;
end
end
%swap the rows
A([i,imax],:)=A([imax,i],:);
end
if A(i,i)==0
% matrix is singular
singular=true;
end
% do for all remaining elements in current row
for j=i+1:r
A(j,:)=A(j,:)-A(i,:)*A(j,i)/A(i,i);
A(j,i)=0; % fill lower triangular matrix with zeros
end
end
% if matrix is non-singular
if singular==false
sol=zeros(r,1);% solution array
% backward susbstitution
for i=r:-1:1
s=A(i,c);% s-> it will become the value of x(i)
for j=r:-1:i+1
s=s-A(i,j)*sol(j,1);% this value needs to be removed from s
end
sol(i,1)=s/A(i,i);% divide by coeff of x(i)
end
else
disp('Matrix is Singular.');
end
end