2013-12-20 120 views
1

在c#中我有四个10x10 int方阵,我需要通过合并四个较小的矩阵来创建一个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]] 
+0

一些代码,请 –

+2

加入他们怎么样? '[[0 1] [2 3]]'还是'[[0 2] [1 3]]'? –

+0

@JuliánUrbano'[[0 1] [2 3]]' – Federico

回答

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

你可以这样做:

// 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)]; 
    } 
} 
相关问题