# pcg

Solve a system of linear equations with the preconditioned conjugate gradient method.

## Syntax

x = pcg(A,b)

x = pcg(A,b,rtol)

x = pcg(A,b,rtol,maxit)

x = pcg(A,b,rtol,maxit,M1)

x = pcg(A,b,rtol,maxit,M1,M2)

x = pcg(A,b,rtol,maxit,M1,M2,x0)

[x, iflag, relres, iter, resvec] = pcg(...)

## Inputs

A
The left-hand side matrix, or a function name or handle to generate A*x. The matrix should be symmetric positive definite.
b
The right-hand side vector.
Dimension: vector
rtol
The relative convergerce tolerance (default: 1.0e-6).
Type: double
Dimension: scalar
maxit
The maximum number of iterations (default: min(size(b, 1), 20)).
Type: integer
Dimension: scalar
M1
The left preconditioner matrix, or a function name or handle to generate M1\x. (default: none or [])
Dimension: matrix
M2
The right preconditioner matrix, or a function name or handle to generate M2\x. (default: none or [])
x0
The initial estimate of the solution (default: zeroes(length(b),1)).
Dimension: vector

## Outputs

x
The solution vector.
iflag
The termination status.
iflag = 0:
The algorithm converged within the allowed tolerance and number of iterations.
iflag = 1:
The algorithm completed the allowed iterations without converging.
iflag = 2:
A preconditioner matrix was singular.
iflag = 3:
The algorithm converged, but not at a solution due to stagnation.
iflag = 4:
The algorithm stopped because behavior indicates that A is not positive definite.
relres
The magnitude of the residual relative to norm(b).
iter
The number of iterations performed.
resvec
The residual vector.

## Example

Case using a function handle for A and a left preconditioner.

M = [1, 2, 0; 4, 5, 6; 0, 8, 9];
A = M' * M;
b = [1; 2; 3];
tol = 0.0001;
max_it = 5;
M1 = diag(diag(A));
M2 = [];
x0 = [];
Ahandle = @(x) A * x;
[x, iflag, relres, iter, resvec] = pcg(Ahandle, b, tol, max_it, M1, M2, x0)
x = [Matrix] 3 x 1
0.04640
-0.16320
0.15840
iflag = 0
relres = 1.04715e-12
iter = 4
resvec = [Matrix] 4 x 2
6.50672e+01  7.12665e+00
1.00361e+00  1.07263e-01
9.39820e-01  1.25481e-01
3.91807e-12  4.26115e-13