Matlab Examples: Matrix Solution Methods
Matlab Examples: Matrix Solution Methods
MATLAB EXAMPLES
Matrix Solution Methods
lu(A) LU decomposition
>> [l u p]=lu(A) p=
l= 1 0 0 0
1.0000 0 0 0 0 1 0 0
0.4286 1.0000 0 0 0 0 1 0
-0.1429 0.2128 1.0000 0 0 0 0 1
0.2857 -0.7234 0.0898 1.0000
13.7473
13.7473
Iterative methods – Jacobi method
The following M-file shows how to use Jacobi method in MATLAB:
(jacobi_example.m) if j==i
% Iterative Solutions of linear euations:(1) Jacobi Method continue
% Linear system: A x = b else
% Coefficient matrix A, right-hand side vector b s=s+A(i,j)*x0(j);
A=[7 3 -1 2; 3 8 1 -4; -1 1 4 -1; 2 -4 -1 6]; end
b= [-1;0;-3;1]; end
% Set initial value of x to zero column vector x1(i)=(b(i)-s)/A(i,i);
x0=zeros(1,4); end
% Set Maximum iteration number k_max if norm(x1-x0)<erp
k_max=1000; break
% Set the convergence control parameter erp else
erp=0.0001; x0=x1;
% Show the q matrix end
q=diag(diag(A)) end
% loop for iterations % show the final solution
for k=1:k_max x=x1
for i=1:4 % show the total iteration number
s=0.0; n_iteration=k
for j=1:4
Iterative methods- Jacobi method
Running M-file in command window:
>> jocobi_r_ex
q=
7 0 0 0
0 8 0 0
0 0 4 0
0 0 0 6
x=
-0.9996 0.9996 -0.9999 0.9996
n_iteration =
60
Iterative methods - Gauss-Seidel method
In the M-file for Gauss-seidel method, the
only difference is the q matrix, which
replaced by: q=tril(A), the codes in Running M-file in command window
the loop changed as the following:
>> gauss_example
for i=1:4 q=
s1=0.0; 7 0 0 0
s2=0.0; 3 8 0 0
if (i==1) continue -1 1 4 0
else 2 -4 -1 6
for j=1:i-1
s1=s1+A(i,j)*x1(j); x=
end -0.9996 0.9997 -0.9999 0.9997
end
for j=i+1:4 n_iteration =
s2=s2+A(i,j)*x0(j); 10
end
x1(i)=(b(i)-s1-s2)/A(i,i);
end
Iterative methods - SOR method
Again, In the M-file for SOR method, the only
difference is the q matrix, which replaced by:
q1=tril(A)-diag(diag(A)); q2=diag(diag(A))/1.4; Run this M-file:
q=q1+q2; Note: the relaxation factor set to 1.4
>> SOR_example
for this case.
q=
for i=1:4 5.0000 0 0 0
s1=0.0; 3.0000 5.7143 0 0
s2=0.0; -1.0000 1.0000 2.8571 0
if (i==1) continue 2.0000 -4.0000 -1.0000 4.2857
else
for j=1:i-1 r=
s1=s1+A(i,j)*x1(j); 1.4000
end
end x=
for j=i+1:4 -0.9996 0.9997 -0.9999 0.9997
s2=s2+A(i,j)*x0(j);
end n_iteration =
x1(i)=r*(b(i)-s1-s2)/A(i,i)+(1.0-r)*x0(i); 12
end
Iterative methods – Conjugate gradient method
Use cgs, pcg to solve above linear equations, the tolerance is 1.0E-6 (default)
>> x=cgs(A,b,0.00001)
cgs converged at iteration 4 to a solution with relative residual 1.2e-015
x=
-1.0000
1.0000
-1.0000
1.0000
>> x=pcg(A,b,0.00001)
pcg converged at iteration 4 to a solution with relative residual 3.1e-016
x=
-1.0000
1.0000
-1.0000
1.0000
Iterative methods - Summary
Method Solution Total Iteration
number
Jacobi method ( -0.9996, 0.9996, -0.9999, 0.9996) 60