5. Relaxation [15 points]: In the appendix below you are given a
MATLAB function that performs Gauss
Seidel (engr3202_gauss_seidel). (a) Upgrade the function by
adding the capability to perform relaxations. (b) Test your code on
the system given in problem 4 (c).
Appendix:
function [x,iter]= engr3202_gauss_seidel(a,b,n,x,imax,es)
%=====================================================================
% List of input %=================== % a: Coefficients matrix % b:
right hand side vector % n: is the number of equations %imax:
maximum number of iterations %e_s: stopping the stopping criteria
for the iterations %the code will stop if iterations>=imax OR
e_stopping is satisfied for one % of the variables x %x: The
initial guess for the unknowns. Zeros should be usually fine. %
List of output %================== % x are the values of the
unknowns %iter: number of iterations
%=====================================================================
% The first loop aims at dividing all the equations by aii, this
will % reduce the computational cost, because we do not need to
divide by it %every iteration. for i=1:n dummy=a(i,i); for j=1:n
a(i,j)=a(i,j)/dummy; end b(i)=b(i)/dummy; end % Next, we will
perform the first iteration separately in one loop, to % provide a
good basis to compute the relative approximate error. for i=1:n
sum=b(i); for j=1:n if i~=j sum=sum-(a(i,j)*x(j)); end end
x(i)=sum; % we updated the value of xi right away in the sprit of
GaussSeidel method. end iter=1; % we just finished the first
iteration %Now we will start the iterative loop of Gauss-Seidel
which will %terminate if the es(stopping criterion) is met FOR all
x's or if the %maximum iterations is met. while(1) sentinel =1; %
This is a useful variable. It is goal is not to keep calculating
the relative error %inside one iteration if already one of the x's
is still have large %error. Since one of the x's has a large error,
we do not need to %calculate the error for the other x's. for i=1:n
old=x(i); %this is used in calculating the relative error.
sum=b(i); for j=1:n if i~=j sum=sum-a(i,j)*x(j); end end x(i)=sum;
% we updated the value of xi right away in the sprit of
Gauss-Seidel method. 5 if sentinel == 1 && x(i)~=0
%Calculate error when needed AND when the denominator is nonzero
ea=abs(((x(i)-old)/x(i))*100); if ea > es %If one of the
variables has large error in this iteration, then do not calculate
%relative error for other variables because it is waste of %time
sentinel = 0; end end end iter=iter+1; % we finished one iteration
if sentinel==1 || iter>=imax break % exit the loop of maximum
iterations met or stopping criterion met for all x's end end
5. Relaxation [15 points]: In the appendix below you are given a MATLAB function that performs Gauss Seidel (engr3202_ga
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am