This repository has been archived on 2021-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
NC/mp5/Project_5_Maggioni_Claudio/myCG.m

27 lines
596 B
Mathematica
Raw Permalink Normal View History

2020-11-25 14:20:13 +00:00
function [x,rvec] = myCG(A, b, x0, max_itr, tol)
x = x0;
rvec = zeros(1,max_itr+1);
r = b - A * x0;
rvec(1) = norm(r, 2);
d = r;
delta_old = dot(r, r);
for i = 1:max_itr
s = A * d;
alpha = delta_old / dot(d, s);
x = x + alpha * d;
r = r - alpha * s;
delta_new = dot(r, r);
beta = delta_new / delta_old;
d = r + beta * d;
delta_old = delta_new;
rvec(i + 1) = delta_new;
if delta_new / norm(b) < tol
2020-11-25 14:20:13 +00:00
rvec = rvec(1:i+1);
break
end
end
end