-
Notifications
You must be signed in to change notification settings - Fork 0
/
conjgrad.m
51 lines (48 loc) · 1.05 KB
/
conjgrad.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function x = conjgrad(A,b,tol)
% CONJGRAD Conjugate Gradient Method.
% X = CONJGRAD(A,B) attemps to solve the system of linear equations A*X=B
% for X. The N-by-N coefficient matrix A must be symmetric and the right
% hand side column vector B must have length N.
%
% X = CONJGRAD(A,B,TOL) specifies the tolerance of the method. The
% default is 1e-10.
%
% Example (highlight lines between %{ and %}, then press F9):
%{
% n = 6000;
% m = 8000;
% A = randn(n,m);
% A = A * A';
% b = randn(n,1);
% tic, x = conjgrad(A,b); toc
% norm(A*x-b)
%}
% By Yi Cao at Cranfield University, 18 December 2008
% Updated on 6 Feb 2014.
%
if nargin<3
tol=1e-10;
end
x = b;
r = b - A*x;
if norm(r) < tol
return
end
y = -r;
z = A*y;
s = y'*z;
t = (r'*y)/s;
x = x + t*y;
for k = 1:numel(b);
r = r - t*z;
if( norm(r) < tol )
return;
end
B = (r'*z)/s;
y = -r + B*y;
z = A*y;
s = y'*z;
t = (r'*y)/s;
x = x + t*y;
end
end