In: Advanced Math
Write your own routine to solve a system of n linear equations and n unknowns using the LU decomposition. Input should take an augmented matrix and the number of equations n. Output should be the augmented matrix. L and U matrices and the solution. Also compare your results to those of Matlab’s built in LU decomposition. Use your code to solve the systems given as (a) and (b) below: a) 3a − 2b + c = −3, a − 4b + 2c + 2d = 6, a + 3b = 5, −3a + 7b + 9c + d = 5
MATLAB Script (Run it as a script, not from command window):
close all
clear
clc
A = [3 -2 1 0;
1 -4 2 2;
1 3 0 0;
-3 7 9 1];
b = [-3 6 5 5]';
n = size(A,1);
Ag = [A b];
fprintf('Using custom
function:\n---------------------------------------------\n')
[Ag,L,U,x] = customLU(n, Ag)
fprintf('\nUsing inbuilt lu()
function:\n---------------------------------------------\n')
[l,u] = lu(A);
x = u\(l\b)
function [Ag_,L,U,x] = customLU(n, Ag)
Ag_ = Ag;
A = Ag(:,1:end-1);
b = Ag(:,end);
L = eye(n);
for i = 1:1:n
L(i+1:n, i) = A(i+1:n, i) / A(i, i);
for j = i+1:1:n
A(j, :) = A(j, :) - L(j, i)*A(i, :);
end
end
U = A;
x = U\(L\b);
end
Output: