如何将四个较小的矩阵“连接”在一起形成一个更大的矩阵?

时间:2013-12-20 14:07:41

标签: c# arrays join matrix int

在c#中,我有四个10x10 int square矩阵,我需要通过合并四个较小的矩阵来创建一个20x20的方阵。

实现这一目标的最佳方法是什么?

编辑:这是我的代码

                int[] first = myArray.Take(myArray.Length / 2).ToArray();
            int[] second = myArray.Skip(myArray.Length / 2).ToArray();

            int[,] matrice0 = MatrixCalc(first, first);
            int[,] matrice1 = MatrixCalc(first, second);
            int[,] matrice2 = MatrixCalc(second, first);
            int[,] matrice3 = MatrixCalc(second, second);
            // Need to join these four matrices here like this: [[0 1][2 3]]

2 个答案:

答案 0 :(得分:1)

快速组合一个简单的不可扩展的解决方案(仅适用于4个矩阵,如果您需要可扩展的解决方案,您可以将矩阵作为列表列表并将其连接起来),假设矩阵长度相同。没有编译它如此抱歉任何错误

int[,] joinedMatrice = new int[matrice0.GetLength(0) + matrice1.GetLength(0), matrice0.GetLength(1) + matrice2.GetLength(1)];

    for (int i = 0; i < matrice0.GetLength(0) + matrice1.GetLength(0); i++)
    {
        for (int j = 0; j < matrice0.GetLength(1) + matrice2.GetLength(1); j++)
        {
            int value = 0;
            if (i < matrice0.GetLength(0) && j < matrice0.GetLength(1))
            {
                value = matrice0[i, j];
            }
            else if (i >= matrice0.GetLength(0) && j < matrice0.GetLength(1))
            {
                value = matrice1[i - matrice0.GetLength(0), j];
            }
            else if (i < matrice0.GetLength(0) && j >= matrice0.GetLength(1))
            {
                value = matrice2[i, j - matrice0.GetLength(1)];
            }
            else if (i >= matrice0.GetLength(0) && j >= matrice0.GetLength(1))
            {
                value = matrice3[i - matrice0.GetLength(0), j - matrice0.GetLength(1)];
            }

            joinedMatrice[i, j] = value;
        }

    }

答案 1 :(得分:1)

你可以这样做:

// pre-arrange them in the form you want
List<List<int[,]>> sources = new List<List<int[,]>>() {
    new List<int[,]>() {matrice0, matrice1},
    new List<int[,]>() {matrice2, matrice3}
};

int[,] joint = new int[20, 20];
for (int i = 0; i < joint.GetLength(0); i++) {
    for (int j = 0; j < joint.GetLength(1); j++) {
        // select the matrix corresponding to value (i,j)
        int[,] source = sources[i / matrice0.GetLength(0)][j / matrice0.GetLength(1)];
        // and copy the value
        joint[i, j] = source[i % matrice0.GetLength(0), j % matrice0.GetLength(1)];
    }
}