Page 229 - MATLAB an introduction with applications
P. 229
214 ——— MATLAB: An Introduction with Applications
4.15 EXAMPLE PROBLEMS AND SOLUTIONS
Example E4.1: Use Gaussian elimination scheme to solve the set of equations.
2x + x – 3x = 11
1
3
2
4x – 2x + 3x = 8
3
1
2
–2x + 2x – x = –6
1
2
3
Solution:
>> A = [2 1 –3;4 –2 3; –2 2 –1];
>> b = [11;8; –6];
>> format long
>> [x,det] = gauss(A,b)
x =
3
–1
–2
det = –22
function [x, det] = gauss(A, b)
% Solves A x = b by Gauss elimination and finds det(A)
*
% USAGE: [x, det] = gauss(A,b)
if size(b, 2) > 1; b = b’; end % b column vector
n = length(b);
for k = 1:n – 1 % Elimination
for i = k + 1:n
if A (i, k) ~ = 0
lambda = A(i, k)/A(k, k);
A(i, k +1:n) = A(i, k +1:n) – lambda * A(k, k + 1:n);
b(i) = b(i) – lambda*b(k);
end
end
end
if nargout == 2; det = prod(diag(A)); end
for k = n: – 1:1 % Back substitution
b(k) = (b(k) – A(k, k + 1:n) * b(k + 1:n))/A(k, k);
end
x = b;