有没有办法在 Math.Net 上支持 0x0 矩阵?

Is there a way to suport 0x0 Matrix on Math.Net?

我正在使用 Matrix Nx2 来存储构成多边形的 Point 列表。

我有一个函数,它 return 一个子矩阵 Nx2 包含点,这些点位于带有简单方程的直线上方,例如 y = 6

问题是有时子矩阵没有点。

然后我想做类似的事情:

using MathNet.Numerics.LinearAlgebra.Double;
double[,] pontos = { { }, { } };
Matrix mat = DenseMatrix.OfArray(pontos);

有没有办法支持0x0Matrix并拥有Matrix.RowCount == 0

你要找的是不可能的。创建任何 Matrix MathNet 时总是会使用构造函数创建 MatrixStorage

// MathNet.Numerics.LinearAlgebra.Storage.MatrixStorage<T>
using MathNet.Numerics.Properties;
using System;
using System.Runtime.Serialization;

protected MatrixStorage(int rowCount, int columnCount)
{
    if (rowCount <= 0)
    {
        throw new ArgumentOutOfRangeException("rowCount", Resources.MatrixRowsMustBePositive);
    }
    if (columnCount <= 0)
    {
        throw new ArgumentOutOfRangeException("columnCount", Resources.MatrixColumnsMustBePositive);
    }
    RowCount = rowCount;
    ColumnCount = columnCount;
}

所以可以看出 MathNet 不可能有 0x0 Matrix

更新:

你可以做这样的破解:

static class EmptyDenseMatrix
{
    public static DenseMatrix Create()
    {
        var storage = DenseColumnMajorMatrixStorage<double>.OfArray(new double[1, 1]);
        var type = typeof(DenseColumnMajorMatrixStorage<double>);
        type.GetField("RowCount").SetValue(storage, 0);
        type.GetField("ColumnCount").SetValue(storage, 0);
        type.GetField("Data").SetValue(storage, new double[0]);

        return new DenseMatrix(storage);
    }
}

用法:

Console.WriteLine(EmptyDenseMatrix.Create());

给出:

DenseMatrix 0x0-Double

但是在 MathNet 中使用这样的矩阵没有任何意义,例如

Console.WriteLine(EmptyDenseMatrix.Create()* EmptyDenseMatrix.Create());

给出:

System.ArgumentOutOfRangeException: The number of rows of a matrix must be positive.