How to create a submatrix skipping a row and a column using Mathnet.numerics library?

妖精的绣舞 提交于 2020-01-06 06:43:46

问题


I am trying to code to obtain minors of different elements in a matrix. I am using Mathnet.numerics library. I see the library has submatrix method where I need to input rowindex and rowcount. But for my case I need to create submatrix by skipping rows and columns (for example, for a 3x3 matrix, for element (1,2), I need to skip the first row and second column to create my submatrix). Any idea how to use the existing functionality of the Mathnet.numerics?


回答1:


You can use RemoveRow and RemoveColumn, which will return a new matrix with the chosen row or column removed. They do not modify the original matrix. Beware that the rows and columns are zero-indexed, i.e. the first row corresponds to index 0.

var m = Matrix<double>.Build.Dense(3,3, (i,j) => 100*i + j);
var m2 = m.RemoveRow(0).RemoveColumn(1);

Returns

m: DenseMatrix 3x3-Double
  0    1    2
100  101  102
200  201  202


m2: DenseMatrix 2x2-Double
100  102
200  202



回答2:


c#
private double[,] getSubMatrix(double[,] _a, int i_start, int i_end, int j_start, int j_end)
    {
        double[,] _nex = new double[i_end - i_start + 1, j_end - j_start + 1];
        for(int i = i_start, i_sub = 0; i <= i_end; i++, i_sub++)
        {
            for(int j = j_start, j_sub = 0; j <= j_end; j++, j_sub++)
            {
                _nex[i_sub, j_sub] = _a[i, j];
            }
        }
        return _nex;
    }

Exampe:

c#
double[,] _a = { {22, 15, 1 },
             {42, 5, 38 },
             {28, 9, 4} };
getSubMatrix(_a, 1, 2, 1, 2);
//If u use MathNet
Console.WriteLine(DenseMatrix.OfArray(getSubMatrix(_a, 1, 2, 1, 2)).ToString());

U will get: {5,38}, {9,4} matrix



来源:https://stackoverflow.com/questions/26452646/how-to-create-a-submatrix-skipping-a-row-and-a-column-using-mathnet-numerics-lib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!