2013-12-20 160 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)]; 
    } 
} 
相關問題