Example 3: Solve a Small Linear System Stored in Sparse Form

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.
import com.imsl.math.*;
public class GenMinResEx3 implements GenMinRes.Function {
    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 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 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]);
        }
        
        GenMinResEx3 atp = new GenMinResEx3();
        
        // 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.