Assignment 2
Question 1
give two commands
>rand("state",student_number);
>rand(1)
Run own output and paste your output here
Question 2
function x = gauss_seidel(A,d,x0,tol,Imax)
% gauss_seidel: implements the Jacobi iterative method
% for solving a system of linear equations.
% Input: A = square coefficient matrix (nxn)
% d = right hand side vector (nx1)
% x0 = initial guess (nx1) (default = zeros)
% tol = stop criterion (default = 10^-6)
% Imax = maximum iterations (default = 100)
% Output: Solution vector.
if nargin<5, Imax=100; end
if nargin<4, tol=10^-6; end
[m,n]=size(A);
if m~=n, error('Matrix A must be square'); end
if nargin<3, x=zeros(n,1); else x=x0; end
C=A;
for i=1:n
C(i,i)=0;
end
for i=1:n
C(i,1:n)=C(i,1:n)/A(i,i);
end
b=zeros(1,n);
for i=1:n
b(i)=d(i)/A(i,i);
end
iter=0;
while true
x_old=x;
for i=1:n
x(i)=b(i)-C(i,:)*x;
if x(i)~=0
err(i)=abs((x(i)-x_old(i))/x(i));
end
end
iter=iter+1;
, if iter>=Imax || norm((x-x_old)./x)<tol
fprintf('Total Iterations are: %d\n',iter);
return
end
end
end
clc
clear all
close all
A=[20,-1,1;2,10,-1;1,1,-20];
b=[20;11;-18];
disp('Solution by backslash is');
x=A\b
disp('Solution by gauss siedel');
x=gauss_seidel(A,b,[1;2;3],1e-7,100)
function x = gauss_seidel(A,d,x0,tol,Imax)
Output:
x =
1.0000
1.0000
1.0000
Question 3
clc
clear all
close all
A=[12,-3,4,-2;1,10,-1,-20;1,-1,20,4;1,1,-20,-3];
b=[12;15;-7;-5];
disp('Solution of part a using backslash is');
A\b
disp('Solution of part a using backslash is');
gauss_seidel(A,b,[1;2;3;4],1e-7,100)
function x = gauss_seidel(A,d,x0,tol,Imax)
% gauss_seidel: implements the Jacobi iterative method
% for solving a system of linear equations.
% Input: A = square coefficient matrix (nxn)
% d = right hand side vector (nx1)
% x0 = initial guess (nx1) (default = zeros)
% tol = stop criterion (default = 10^-6)
% Imax = maximum iterations (default = 100)