Question1 (50pts): LU Factorization Code for SquareMatrices without Row Exchange
I want you to write an LU decomposition program in Matlab forsquare matrices (n×n) where row exchange is not necessary (that isno pivot is 0). Here are some hints and requirements for yourmatlab code.
You should write comments for every procedure. Make sure thatyour code is well indexed (see below). Otherwise it will be hardfor me to follow and bad programming practice for you.
This should be a Matlab Function calledslu (don’t name itlu because matlab already has a programcalled lu):
Your program should be a function in Matlab. So your filenameshould be slu.m (.m is standard for matlab scripts or functions).In order to be a function you should start with
function [L,U]=slu=slu(A)
where A is the input square matrix. Always write what a programdoes using matlab
comment (%) so that it
First step is to determine the size of the matrix. Use sizecommand to obtain the size of a matrix.
[n,m]=size(A)
Then if n is not equal to m end the program. If n=m continue
So your code should look like this
function [L,U]=slu=slu(A)
%LU factorization of square matrices %with no row exchange
[n,n]=size(A) %determine the size of A Tol=1.e-6 %tolerance levelfor zero
for k=1:n %loop over pivots of A if(A(k,k) < tol) %check forpivot
disp(‘cannot proceed without row exchange’) end %cannot proceedwithout row exchange L(k,k)=1;
for i=k+1:n %loop over each line to determine lik determinelik
for j=k:n start from row k+1 and col. k remove (pivot row×Lik)from each row of A
end
for j=k:n
write the pivot line to Ubecause pivot is fixed
end end
due 23/10/2019
Question2(50pts): Solving matrix equation usingLU
Next step is to solve the equation using substitution. So youwill need to do the standard procedure for LU. First step is tosolve Ly=b. And next is to solve Ux=y. For Ly=b you need to go fromtop to bottom, but for Ux=y you need to go from bottom xn to x1.This function will use slu function so you need to be on the samedirectory. Name your file “luslv.m”.
Function x=luslv(A,b)
%Solve Ax=b using L&U from slu(A) %No row exchanges
[L,U]=slu(A) %first decompose A to LU
First do a for loop from k=1:n and another for loop for j=1:k-1and sum the contributions to b(k) from yk-1, yk-2...y1.
Then y(k)=b(k)-s %forward elim. To solve Ly=b
Then solve Ux=y. You need to start from n and go to 1. In matlabyou can do it
for k=n:-1:1 %go backwards from n to 1
Sum up contributions from xk+1, xk+2...xn.
Remove the sum from y(k) and divide by the pivot