1

Using Math.Net Numerics, how can I index parts of a matrix?

For example, I have a collection of ints and I want to get a submatrix with the rows and columns chosen accordingly.

A[2:3,2:3] should give me that 2 x 2 submatrix of A where the row index and the column index is either 2 or 3

elina
  • 11
  • 1
  • 3

2 Answers2

1

Just use some thing like

var m = Matrix<double>.Build.Dense(6,4,(i,j) => 10*i + j);
m.Column(2); // [2,12,22,32,42,52]

to access the desired column use the Vector<double> Column(int columnIndex) extension method.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277
  • Thanks. But what if I want just parts of the 2nd column? – elina Jun 03 '15 at 10:49
  • Well use the index notation for matricies `M[i, j]` for row and column `i` and `j`. I have just read your updated question and it makes no sense. You cannot get a sub-MATRIX od a vector. Vectors are essentally a single column/row matrix. MathNET is very well documented, my suggestion is to download the source code and look through the test project... – MoonKnight Jun 03 '15 at 11:36
  • Ok, thanks. Maybe not a Submatrix of a vector, but a submatrix of an array of ints? – elina Jun 03 '15 at 12:20
  • Math.Net's `subMatrix` method for matrices will easily give you submatrices. See examples at See https://numerics.mathdotnet.com/Matrix.html (Which is where this one seems to come from) – FXQuantTrader Oct 08 '19 at 03:01
0

I suspect you were looking for something like this Extension method.

public static Matrix<double> Sub(this Matrix<double> m, int[] rows, int[] columns)
{
    var output = Matrix<double>.Build.Dense(rows.Length, columns.Length);
    for (int i = 0; i < rows.Length; i++)
    {
        for (int j = 0; j < columns.Length; j++)
        {
            output[i,j] = m[rows[i],columns[j]];
        }
    }

    return output;
}

I've omitted the exception handling to ensure rows and columns are not null.

gwizardry
  • 501
  • 1
  • 6
  • 19