Code Monkey home page Code Monkey logo

Comments (4)

wo80 avatar wo80 commented on August 10, 2024 1

CSparse has no method supporting this, but the following code might get you started:

/// <summary>
/// Create a sparse matrix from given diagonals.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="A">The input diagonals stored column-wise.</param>
/// <param name="diags">The diagonal offsets.</param>
/// <param name="rowCount">The target matrix row count.</param>
/// <param name="columnCount">The target matrix column count.</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
static CompressedColumnStorage<T> spdiags<T>(DenseColumnMajorStorage<T> A, int[] diags,
    int rowCount, int columnCount) where T : struct, IEquatable<T>, IFormattable
{
    int k = diags.Length;

    if (A.ColumnCount != k)
    {
        throw new ArgumentException("Columns of A must correspond to diagonals.");
    }

    int dim = Math.Min(rowCount, columnCount);

    var coo = new CoordinateStorage<T>(rowCount, columnCount, k * dim);

    // Stores current column of A.
    var column = new T[A.RowCount];

    for (int i = 0; i < k; i++)
    {
        A.Column(i, column);

        int d = diags[i];

        int ik = d < 0 ? -d : 0;
        int jk = d > 0 ?  d : 0;

        int len = dim - Math.Abs(d);

        int offset = d > 0 ? d : 0;

        for (int j = 0; j < len; j++)
        {
            coo.At(ik++, jk++, column[offset + j]);
        }
    }

    return CompressedColumnStorage<T>.OfIndexed(coo, true);
}

Here's an example how to use it:

var A = DenseMatrix.OfColumnMajor(4, 3, new double[]
{
    -1, -1, -1, -1,
     2,  2,  2,  2,
    -1, -1, -1, -1
});

var B = spdiags(A, new int[] { -1, 0, 1 }, 4, 4);

The above implementation will most likely fail for non-square target matrices (rowCount != columnCount). Feel free to improve it and post your code or do a pull request.

from csparse.net.

wo80 avatar wo80 commented on August 10, 2024 1

Here's another version, which should perform better for large matrices and should work with non-square matrices:

public static CompressedColumnStorage<T> OfDiagonals(DenseColumnMajorStorage<T> A, int[] diags,
    int rowCount, int columnCount)
{
    int k = diags.Length;

    if (A.ColumnCount != k)
    {
        throw new ArgumentException("Columns of A must correspond to diagonals.");
    }

    // Upper limit for storage size.
    int size = k * Math.Min(rowCount, columnCount);

    // Current non-zeros count.
    int nz = 0;

    var result = Create(rowCount, columnCount, size);

    var ap = result.ColumnPointers;
    var ai = result.RowIndices;
    var ax = result.Values;

    // Fill each column of the result matrix.
    for (int col = 0; col < columnCount; col++)
    {
        ap[col] = nz;

        // Add diagonals at specified offsets.
        for (int j = 0; j < k; j++)
        {
            int row = col - diags[j];

            if (row >= 0 && row < rowCount)
            {
                ai[nz] = row;
                ax[nz] = A.At(col, j);

                nz++;
            }
        }
    }

    ap[columnCount] = nz;

    Helper.SortIndices(result);

    return result;
}

// Copied from CompressedColumnStorage.cs
static CompressedColumnStorage<T> Create(int rowCount, int columnCount, int valueCount)
{
    if (typeof(T) == typeof(double))
    {
        return new CSparse.Double.SparseMatrix(rowCount, columnCount, valueCount)
            as CompressedColumnStorage<T>;
    }

    if (typeof(T) == typeof(Complex))
    {
        return new CSparse.Complex.SparseMatrix(rowCount, columnCount, valueCount)
            as CompressedColumnStorage<T>;
    }

    throw new NotSupportedException();
}

from csparse.net.

lilkui avatar lilkui commented on August 10, 2024 1

Thanks a million. On my machine, the second version is about 2.5x faster for smaller matrices and 4x faster for larger matrices.

from csparse.net.

wo80 avatar wo80 commented on August 10, 2024

Updated nuget package available now.

from csparse.net.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.