Question: function x = ConjugateGradientMethod ( A , b , x 0 , tol, max _ iter ) % Conjugate Gradient Method to solve Ax =

function x = ConjugateGradientMethod(A, b, x0, tol, max_iter)
% Conjugate Gradient Method to solve Ax = b
if nargin <4
tol =1e-10;
end
if nargin <5
max_iter = length(b);
end
% Initial Setup
r = b - A * x0;
p = r;
rs_old = r'* r;
x = x0;
% Iterate
for k =1:max_iter
Ap = A * p;
alpha = rs_old /(p'* Ap);
x = x + alpha * p;
r = r - alpha * Ap;
rs_new = r'* r;
if sqrt(rs_new)< tol
break;
end
p = r +(rs_new / rs_old)* p;
rs_old = rs_new;
end
end
% My student ID is 723113010001
student_id =723113010001;
last_two_digits = mod(student_id,100);
% Size of the problem
n1=200+ last_two_digits; % For the first problem
n2=400+ last_two_digits; % For the second problem
% Create matrix A and vector b for the first problem
A1= diag(-2* ones(n1,1))+ diag(ones(n1-1,1),1)+ diag(ones(n1-1,1),-1);
b1= zeros(n1,1);
b1(1)=-1;
b1(end)=-1;
% Create matrix A and vector b for the second problem
A2= diag(-2* ones(n2,1))+ diag(ones(n2-1,1),1)+ diag(ones(n2-1,1),-1);
b2= zeros(n2,1);
b2(1)=-1;
b2(end)=-1;
% Initial guess
x0_1= zeros(n1,1);
x0_2= zeros(n2,1);
% Solve using conjugate gradient method
x1= ConjugateGradientMethod(A1, b1, x0_1);
x2= ConjugateGradientMethod(A2, b2, x0_2);
% Display solutions
disp('Solution for the first problem (n =201):');
disp(x1);
disp('Solution for the second problem (n =401):');
disp(x2);
correct the code to remove parse errors

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!