1

Im using MathNet.Numerics package for matrix calculation.

For matrix declaration and initialization the expected code is as follows:

Matrix<double> A = DenseMatrix.OfArray(new double[,] {
        {1,1,1,1},
        {1,2,3,4},
        {4,3,2,1}});

In my own code, I have three one-dimensional arrays - xPointsSquared, yPoints, one.

I get the error - "a nested array initializer is expected" when trying to initialize the matrix in this following way,

Matrix<double> A = DenseMatrix.OfArray(new double[,] {
        xPointsSquared,
        yPoints,
        one});
DazedNConfused
  • 189
  • 2
  • 13

2 Answers2

1

2D array must be initialized with nested array initializer. And it is not the same with initializing jagged array double[][]. What you do in the second case is for initializing jagged array, not for initializing 2D array. If you want to initialize your 2D array by your three one-dimensional array, you have to insert the array element one by one.

Matrix<double> A = DenseMatrix.OfArray(new double[,] {
    { xPointsSquared[0], xPointsSquared[1], xPointsSquared[2], xPointsSquared[3] },

    {yPoints[0], yPoints[1], yPoints[2], yPoints[3],},
    {one[0],one[1],one[2],one[3]}});

My suggestion for your case is to make for loop to insert elements to double[,] first before using the double[,] as input for Matrix class constructor.

double[,] mat = new double[3,3600];
for(int i = 0; i < 3600;++i{
    mat[0,i] = xPointsSquared[i];
    mat[1,i] = yPoints[i];
    mat[2,i] = one[i];
}

Matrix<double> A = DenseMatrix.OfArray(mat);
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Ah! so is there no way around it? Because i have 3600 elements in each array. – DazedNConfused Apr 23 '16 at 03:24
  • You could use for loop to insert the elements to double[,] first before making the double[,] as input for your Matrix – Ian Apr 23 '16 at 03:27
  • While this is technically working, it is not needed. Math.NET provides functions to create matrices directly from (jagged) row arrays as well. See my answer. – Christoph Rüegg Apr 23 '16 at 04:10
1

I'd suggest to use a more appropriate construction function instead, for example:

Matrix<double> A = CreateMatrix.DenseOfRowArrays(xPointsSquared, yPoints, one);

See Creating Matrices and Vectors in the docs for more alternatives.

Christoph Rüegg
  • 4,626
  • 1
  • 20
  • 34