# Matlab: Gaussian elimination function

```
function x = Gauss_Elimination(A,b)
n = length(b);
x = zeros(n,1);
% Forward Elimination
for i = 1:n-1
for j = i+1:n
mul = A(j,i)/A(i,i); % Multiplier
for k = i+1:n
A(j,k) = A(j,k) - mul*A(i,k);
end
b(j) = b(j) - mul*b(i);
end
end
x(n) = b(n)/A(n,n); % Obtain solution for the last variable
% Back Substitution
for i = n-1:-1:1
sum = b(i);
for j = i+1:n
sum = sum - A(i,j)*x(j);
end
x(i) = sum/A(i,i);
end
```

When A = [0 1 1 1; 3 0 3 -4; 1 1 1 2; 2 3 1 3]; b = [0; 7; 6; 6]; x = [4; -3; 1; 2]

However, when I use this function, x = [NAN; NAN; NAN; NAN].

Has anyone told me the reason ???

source to share

Try using breakpoints to see the value of the variables at each iteration. The problem is with the variable "mul", you are dividing something / 0-> infinitely. This is why you are getting these results. If you installed

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

you get the answer: ans =

-4.7273 1.7273 6.4545 1.2727

Hope this helps.

source to share

You can download this code here

https://github.com/pavdpr/matlab-latex/blob/master/RRE.m

It does a gaussian exception and then writes it to LaTex. you can cut the entry into latex and just look at the code that preforms the elimination.

And python version of the same code if you want it

source to share