I am working on a program which needs matrix operation. I decided to use Math.NET Numerics
library. I have a Matrix
and I want to change one of it's values, but I don't know how.
My question is, can we have a Matrix
as an array
?
Can we transform a Matrix
into an array
?
I examined AsArray
method in this library but the return value was null.
-
1Please show us a [mcve]. – Jul 30 '19 at 13:10
1 Answers
Matrix<T>
(which is the base type for all other MathNet
matrix-types) provides an indexer public T this[int row, int column] { get; set; }
. So you can use it to change values of elements.
using MathNet.Numerics.LinearAlgebra.Double;
// ...
var matrix = DenseMatrix.Create(2, 2, 0);
Console.WriteLine(matrix);
matrix[1, 1] = 1;
Console.WriteLine(matrix);
Gives:
DenseMatrix 2x2-Double
0 0
0 0
DenseMatrix 2x2-Double
0 0
0 1
To turn Matrix<T>
into T[,]
use ToArray()
instead of AsArray()
.
MathNet
documentation says that AsArray()
Returns the internal multidimensional array of this matrix if, and only if, this matrix is stored by such an array internally. Otherwise returns null. Changes to the returned array and the matrix will affect each other. Use ToArray instead if you always need an independent array.
Whereas ToArray()
Returns this matrix as a multidimensional array. The returned array will be independent from this matrix. A new memory block will be allocated for the array.
Update:
Looks like AsArray()
does not work at all. With var data = new[,] { { 1d, 1d }, { 1d, 1d } }
new DenseMatrix(DenseColumnMajorMatrixStorage<double>.OfArray(data)).AsArray()
returns null
. So does DenseMatrix.OfArray(data).AsArray()
.
Update2:
Checked with ILSpy
.
MathNet.Numerics.LinearAlgebra.Matrix:
/// <summary>
/// Returns the internal multidimensional array of this matrix if, and only if, this matrix is stored by such an array internally.
/// Otherwise returns null. Changes to the returned array and the matrix will affect each other.
/// Use ToArray instead if you always need an independent array.
/// </summary>
public T[,] AsArray()
{
return Storage.AsArray();
}
MathNet.Numerics.LinearAlgebra.Storage.MatrixStorage:
public virtual T[,] AsArray()
{
return null;
}
Matrix<T>.AsArray()
ALWAYS returns null
.

- 3,177
- 6
- 19
- 37