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.
using System;
using Imsl.Math;
public class GenMinResEx4 : GenMinRes.IPreconditioner
{
    private static SparseMatrix A;
    private static 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};
    private static double[] b = {10.0, 7.0, 45.0, 33.0, -34.0, 31.0};
    private static double[] xguess = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
    private static double[] diagin = {0.1, 0.1, 0.066666666666667, 0.1, 
                                      1.0, 0.1666666666666667};
    private static int[] irow = {5, 1, 2, 1, 3, 3, 4, 4, 4, 4, 0, 5, 5, 1, 3};
    private static int[] jcol = {5, 1, 2, 2, 3, 4, 0, 5, 3, 4, 0, 0, 1, 3, 0};
    
    public virtual void  Amultp(double[] p, double[] z)
    {
        double[] result;
        result = Imsl.Math.SparseMatrix.Multiply(A, p);
        Array.Copy(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)
    {
        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.00000000000001  
5  6                 


Link to C# source.