Practical Work N°3(Solution)
Practical Work N°3(Solution)
% Number of variables
n = length(b);
x = zeros(n, 1);
Exercise 2:
function x = gaussian_elimination(A, b)
% Combine A and b into an augmented matrix
Ab = [A b]
n = length(b);
% Forward elimination
for i = 1:n
% Partial pivoting
[~, maxIdx] = max(abs(Ab(i:n, i)))
maxIdx = maxIdx + i - 1
if maxIdx ~= i
% Swap rows
Ab([i, maxIdx], :) = Ab([maxIdx, i], :);
end
% Make upper triangular
for j = i+1:n
1
University of Algiers 1
Computer Science department
Numerical Methods Practical Work
2nd-year undergraduate students
disp(Ab);
end
AA=Ab(1:n,1:n);
bb=Ab(:,n+1);
disp(AA);
disp(bb);
% Back substitution
x = zeros(n, 1);
for i = n:-1:1
x(i)=(b(i)-AA(i,:)*x)/AA(i,i);
% or x(i) = (Ab(i, end) - Ab(i, 1:n) * x) / Ab(i, i);
fprintf('x%d = %f\n',i,x(i));
end
disp('The solution X = ');
disp(x);
disp(A);
disp(b);
disp('the solution is x=');
disp(x);
Exercise 3:
function x = gauss_jordan_solver(A, b)
% Combine A and b into an augmented matrix
Ab = [A b];
n = length(b);
% Gauss-Jordan elimination
for i = 1:n
% Partial pivoting
2
University of Algiers 1
Computer Science department
Numerical Methods Practical Work
2nd-year undergraduate students
x = Ab(:, end);
end
% Testing the function Ex3 (New script)
A = [2 1 -1; -3 -1 2; -2 1 2];
b = [8; -11; -3];
x = gauss_jordan_solver(A, b);
disp(A);
disp(b);
disp('the solution is x=');
disp(x);
Exercise 4:
function x = lu_solver(A, b)
% LU decomposition
[L, U, P] = lu(A);
b=P*b;
% Solve L*y = b for y (forward substitution)
y = zeros(size(b));
n = length(b);
for i = 1:n
y(i) = (b(i) - L(i,:) *y) / L(i, i);
end
disp(A);
disp(b);
disp('the solution is x=');
disp(x);