Example 4: Solve a Small Linear System Stored in Sparse Form With Preconditioning

A solution to a small linear system in which the coefficient matrix has been stored in SparseMatrix form is found. An initial guess of ones is set before solving the system and preconditioning is used.
import com.imsl.math.*;
public class GenMinResEx4 implements GenMinRes.Preconditioner {
    static private SparseMatrix A;
    static private double a[] = {6.0, 10.0, 15.0, -3.0, 10.0, 
                                 -1.0, -1.0, -3.0, -5.0, 1.0, 
                                 10.0, -1.0, -2.0, -1.0, -2.0};
    static private double b[] = {10.0, 7.0, 45.0, 33.0, -34.0, 31.0};
    static private double xguess[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
    static private double diagin[] = {0.1, 0.1, 0.066666666666667, 
                                      0.1, 1.0, 0.1666666666666667};
    static private int irow[] = {5, 1, 2, 1, 3, 3, 4, 4, 4, 4, 0, 5, 5, 1, 3};
    static private int jcol[] = {5, 1, 2, 2, 3, 4, 0, 5, 3, 4, 0, 0, 1, 3, 0};
    
    public void amultp(double p[], double z[]) {
        double[] result;
        result = A.multiply(A,p);
        System.arraycopy(result, 0, z, 0, z.length);
    }
    
    public void preconditioner(double r[], double z[]) {
        int n = z.length;
        for (int i = 0;  i < n;  i++) {
            z[i] = diagin[i] * r[i];
        }
    }
    
    public static void main(String args[]) throws Exception {
        int       n = 6;
        
        A = new SparseMatrix(n,n);
        for (int i=0; i<a.length;i++) {
            A.set(irow[i], jcol[i], a[i]);
        }
        GenMinResEx4 atp = new GenMinResEx4();
        
        // Construct a GenMinRes object
        GenMinRes gnmnrs = new GenMinRes(n, atp);
        gnmnrs.setGuess(xguess);
        // Solve Ax = b
        new PrintMatrix("x").print(gnmnrs.solve(b));
    }
}

Output

  x
   0  
0  1  
1  2  
2  3  
3  4  
4  5  
5  6  

Link to Java source.