using matlab Write your own routine for Gaussian elimination without any pivoting. Input for the routine should consist of the number (n) of equations and the augmented matrix. Output should be the vector solution of the system. Test your code by using it to solve the following two problems: a) x + y + w + z = 10, 2x + 3y + w + 5z = 31, −x + y − 5w + 3z = −2, 3x + y + 7w − 2z = 18
MATLAB Code:
close all
clear
clc
% x + y + w + z = 10
% 2x + 3y + w + 5z = 31
% −x + y − 5w + 3z = −2
% 3x + y + 7w − 2z = 18
A = [ 1 1 1 1;
2 3 1 5;
-1 1 -5 3;
3 1 7 -2];
b = [10 31 -2 18]';
Ag = [A b];
n = size(A, 1);
x = gauss_elim(n, Ag)
function x = gauss_elim(n, Ag)
A = Ag(:,1:end-1);
b = Ag(:,end);
nb = length(b);
x = zeros(1,n);
% Gaussian elimination
for i = 1:n-1
if A(i,i) == 0
t = min(find(A(i+1:n,i) ~= 0) + i);
if isempty(t)
disp ('Error: A matrix is singular');
return
end
temp = A(i,:); tb = b(i);
A(i,:) = A(t,:); b(i) = b(t);
A(t,:) = temp; b(t) = tb;
end
for j = i+1:n
m = -A(j,i) / A(i,i);
A(j,i) = 0;
A(j,i+1:n) = A(j,i+1:n) + m*A(i,i+1:n);
b(j) = b(j) + m*b(i);
end
end
% Back substitution
x(n) = b(n) / A(n,n);
for i = n-1:-1:1
x(i) = (b(i) - sum(x(i+1:n) .* A(i,i+1:n))) / A(i,i);
end
end
Output:
x =
1 2 3 4
Get Answers For Free
Most questions answered within 1 hours.