Skip to content
wo80 edited this page Jun 8, 2015 · 5 revisions

This example shows how to create a sparse QR factorization:

using CSparse;
using CSparse.Double;
using CSparse.Double.Factorization;
using CSparse.IO;
using System;

public static class Example
{
    public static bool Solve(string filePath)
    {
        // Load matrix from a file.
        var A = MatrixMarketReader.ReadMatrix<double>(filePath);

        int m = A.RowCount;
        int n = A.ColumnCount;

        // Create test data.
        var x = Vector.Create(n, 1.0);
        var b = new double[m];
        var r = new double[m];

        // Compute right hand side vector b.
        A.Multiply(1.0, x, 0.0, b);

        // Apply column ordering to A to reduce fill-in.
        var order = ColumnOrdering.MinimumDegreeAtA;

        var qr = new SparseQR(A, order);

        if (m == n)
        {
            // Solve Ax = b.
            Vector.Copy(b, x);
            qr.Solve(x);
        }
        else if (m > n)
        {
            // Compute min norm(Ax - b).
            var xc = Vector.Clone(b);
            qr.Solve(xc);

            Vector.Copy(xc, x, Math.Min(m, n));
        }
        else
        {
            return false;
        }

        // Compute residual r = b - Ax.
        Vector.Copy(b, r);
        A.Multiply(-1.0, x, 1.0, r);

        return true;
    }
}
Clone this wiki locally