MATLAB Source Code: 'Please Enter Matrix:'

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

MATLAB Source Code

% Ask user to enter input matrix


a=input('Please enter matrix:');
display(a)
% Find dimensions of input matrix
[m,n] = size(a);
%m is number of row,n is number of column
% If input matrix is not square, stop function
if m ~= n
%if number of row is not equal to the number of column
disp('This is not a Square Matrix')
end
% If input matrix is square,use forward elimination
U=a;
L=a;
if m == n
%if number of row equal to the number of column
for j = 1:n-1
%j is column of matrix
for i = j+1:n
%i is row of matrix
f= U(i,j)/U(j,j);
%f is factor
U(i,j:n)=U(i,j:n)-f*U(j,j:n);
% to get U matrix of LU
L(i,j)= f;
%To get L matrix of LU
end
end
for j=1:n
L(j,j)= 1;
%To get L matrix of LU
end
for i=1:n-1
for j=i+1:n
L(i,j:n)=0;
%To get L matrix of LU
end
end
% to find inverse matrix of a
di=eye(n); % identity matrix to find inverse of matrix a
xi=eye(n); % inverse of matrix a using an identity matrix for starting
matrix
i=1;
j=1;
z=1; %the column of the identity matrix
c=0;
y=0;
d=di(:,1);
x=xi(:,1);
while z<=n
%solve Ld=b using forward substitution
while i<=n
while j<=n
if i~=j
c=L(i,j)*d(j)+c;
j=j+1;
else

j=j+1;
end
end
b=di(:,z);
d(i)=(b(i)-c)/L(i,i);
i=i+1;
c=0;
j=1;
end
%solve Ux=d using backward substitution
i=n;
j=n;
while i>0
while j>0
if j~=i
y=a(i,j)*x(j)+y;
j=j-1;
else
j=j-1;
end
end
x(i)=(d(i)-y)/U(i,i);
xi(i,z)=x(i);
i=i-1;
j=n;
y=0;
end
z=z+1;
i=i+1;
end
display(xi) %display inverse of matrix a
end

Flow chart
Start

Input Matrix, a

If square matrix
m=n
m=no. of row
n= no. of column

Output
No Inverse of Matrix a

TRUE

for j=1:n

FALSE

for j = 1:n-1
j = column of matrix

To get L matrix
L(j,j)= 1

for i = j+1:n
i = row of matrix

for i=1:n-1

f= U(i,j)/U(j,j)
f = factor
U= U matrix of LU
for j=i+1:n

Get U matrix of LU
U(i,j:n)=U(i,j:n)-f*U(j,j:n)
To get L matrix
L(j,j)= 1

Do LU decomposition method
to find inverse of matrix a by
using forward substitution and
backward substitution

Get L matrix of LU
L(i,j:n)=f

Output
Determinant of Matrix a

End

You might also like