从对角线不为零的矩阵中提取子矩阵

时间:2019-07-21 17:25:38

标签: c# matrix math.net

我是C#的新手,并且正在使用matrix软件包来与Math.Net合作。 我的matrix如下图所示:

https://imgur.com/a/xzBgISA

我想做的是提取大小为submatrices的所有4x4,其对角线上的值与零不同。我在照片上涂了颜色。

1 个答案:

答案 0 :(得分:0)

const int height = 8;
const int width = 7;

var matrix = DenseMatrix.OfArray(new double[height, width]
{
    { 1, 0, 0, 0, 0, 0, 0 },
    { 0, 1, 0, 0, 0, 0, 0 },
    { 0, 1d/2, 1d/2, 0, 0, 0, 0 },
    { 0, 0, 2d/3, 1d/3, 0, 0, 0 },
    { 0, 0, 0, 1, 0, 0, 0 },
    { 0, 0, 0, 0, 1, 0, 0 },
    { 0, 0, 0, 0, 0, 1, 0 },
    { 0, 0, 0, 0, 0, 0, 1 }
});

var size = 4;
var submatrices =
    // for all possible starting points
    Enumerable.Range(0, height - size + 1).SelectMany(Row =>
        Enumerable.Range(0, width - size + 1).Select(Column => new { Row, Column }))
    // find 4x4 submatrices
    .Select(p => matrix.SubMatrix(p.Row, size, p.Column, size))
    // where all diagonal elements are not zero
    .Where(submatrix => submatrix.Diagonal().All(e => e != 0));

foreach (var submatrix in submatrices)
    Console.WriteLine(submatrix);

结果:

DenseMatrix 4x4-Double
1    0         0         0
0    1         0         0
0  0,5       0,5         0
0    0  0,666667  0,333333

DenseMatrix 4x4-Double
0,5       0,5         0  0
  0  0,666667  0,333333  0
  0         0         1  0
  0         0         0  1

DenseMatrix 4x4-Double
0,666667  0,333333  0  0
       0         1  0  0
       0         0  1  0
       0         0  0  1

DenseMatrix 4x4-Double
1  0  0  0
0  1  0  0
0  0  1  0
0  0  0  1