# Getting the intermediate solutions in an iterative solver

3 views (last 30 days)
Nathan on 16 Jul 2017
Answered: Josh Meyer on 23 Sep 2019
I would like Matlab's iterative solvers to return the solution every 100 or so iterations. IS there a way to do this?

Walter Roberson on 16 Jul 2017
Sorry, that is not possible for qmr or pcg.

Josh Meyer on 23 Sep 2019
While the functions themselves don't return intermediate results, consider that the resvec output of all the iterative solvers returns the history of the relative residual, which tells you how good all of the intermediate solutions were:
[x,flag,relres,iter,resvec] = pcg(A,b);
If that doesn't satisfy your needs, you can get the intermediate results programmatically by calling PCG in a for-loop. Each call to PCG does a few iterations and stores the calculated solution, then you use that solution as the initial vector for the next iteration. For example, this code performs 100 iterations ten times and returns the solution vector every 100 iterations in a cell array:
A = sprand(1000,1000,0.1);
A = A'*A;
b = full(sum(A,2));
x0 = zeros(size(A,2),1);
tol = 1e-8;
maxit = 100;
for k = 1:10
[x,flag,relres] = pcg(A,b,tol,maxit,[],[],x0);
X{k} = x;
R(k) = relres;
x0 = x;
end
After you run this, X{k} is the solution vector computed at iteration k, and R(k) is the relative residual of that solution. (The coefficient matrix in this example is not interesting and was just chosen to make the code run)