0% found this document useful (0 votes)
8 views

Lab-Chapter 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lab-Chapter 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Numerical Analysis Chapter 2: System of linear equations Matlab algorithms

To solve a system of linear equations using MATLAB, the following codes are possible:
1. \ operator and inv( ) commands.

Example 1:
A=[0 1 1;2 -1 -1;1 1 -1]; b=[2 0 1]'; % Eq.(2.2.9)
tic, x1=A\b , toc Tic, toc commands are useful to check the
elapsed time for performing an algorithm.
x1 =

1.0000
1.0000
1.0000

Elapsed time is 0.000212 seconds.


>> tic, x2=inv(A)*b, toc

x2 =

1
1
1

Elapsed time is 0.000400 seconds.

2. Gauss elimination method


Numerical Analysis Chapter 2: System of linear equations Matlab algorithms
Numerical Analysis Chapter 2: System of linear equations Matlab algorithms

function y = Gauss_fcn(a)
% Code from “Gauss elimination
[m,n]=size(a);
for j=1:m-1
for z=2:m
if a(j,j)==0
t=a(j,:);a(j,:)=a(z,:);a(z,:)=t;
end
end
for i=j+1:m
a(i,:)=a(i,:)-a(j,:)*(a(i,j)/a(j,j));
end
end
x=zeros(1,m);
for s=m:-1:1
c=0;
for k=2:m
c=c+a(s,k)*x(k);
end
x(s)=(a(s,n)-c)/a(s,s);
end
%display the results of the gauss elimination method;
y = x';
______________________________________________________________________________
Example 2:
A=[0 1 1;2 -1 -1;1 1 -1]; b=[2 0 1]'; a=[A b];
tic, x=Gauss_fcn(a), toc

x=

1.0000
1.0000
1.0000
Elapsed time is 0.000594 seconds.

3. LU factorization

Example 3:
Ax=b
But, A=LU
LUx=b→ 𝑥 = 𝑈 −1 𝐿−1 𝑏
A = [ 1 2 3;4 5 6;7 8 0 ]; b=[2 0 1]';
To see the LU factorization, call lu with two output arguments.

[L1,U] = lu(A)
Numerical Analysis Chapter 2: System of linear equations Matlab algorithms

L1 =
0.1429 1.0000 0
0.5714 0.5000 1.0000
1.0000 0 0

U=
7.0000 8.0000 0
0 0.8571 3.0000
0 0 4.5000
x= inv(U)*inv(L1)*b

You might also like