-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCG.m
59 lines (43 loc) · 1.07 KB
/
CG.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
52
53
54
55
56
57
58
59
%% REFERENCE
% https://en.wikipedia.org/wiki/Conjugate_gradient_method
%%
function [x, obj] = CG(A,b,x,n,COST,bfig)
if (nargin < 6)
bfig = false;
end
if (nargin < 5 || isempty(COST))
COST.function = @(x) (0);
COST.equation = [];
end
if (nargin < 4)
n = 1e2;
end
% r = b - A*x;
r = b - A(x);
p = r;
rsold = r(:)'*r(:);
obj = zeros(n, 1);
for i = 1:n
% Ap = A*p;
Ap = A(p);
a = rsold/(p(:)'*Ap(:));
x = x + a*p;
r = r - a*Ap;
rsnew= r(:)'*r(:);
if (sqrt(rsnew) < eps)
break;
end
p = r + (rsnew/rsold)*p;
rsold= rsnew;
obj(i) = COST.function(x);
if bfig
figure(1); colormap gray;
subplot(121); imagesc(abs(x)); title([num2str(i) ' / ' num2str(n)]);
subplot(122); semilogy(obj, '*-'); title(COST.equation); xlabel('# of iteration'); ylabel('Objective');
xlim([1, n]); grid on; grid minor;
drawnow();
end
end
x = gather(x);
obj = gather(obj);
end