2011-10-10 57 views
3

我有兩個數組mat1 & Mat2。 我想要new_mat = [ma1,mat2]; 我寫了一個可以工作的函數。我不知道是否有一個非常大的矩陣有效的函數,或者我怎樣才能用Array.CopyTo方法。連接一個二維數組

public static double[,] Concatenate_matrix_byCol(double[,] Mat1, double[,] Mat2) 
{ 
    int col1=Mat1.GetLength(1); 
    int col2 = Mat2.GetLength(1); 
    int row1=Mat1.GetLength(0); 
    int row2 = Mat2.GetLength(0); 
    int i, j, y; 
    double[,] newMat = new double[row1, col1 + col2]; 

    for (i = 0; i < row1; i++) 
    { 
     for (j = 0; j < col1; j++) 
     { 
      newMat[i, j] = Mat1[i, j]; 
     } 
    }     
    for (i = 0; i < row1; i++) 
    { 
     for (y = 0; y < col2; y++) 
     { 
      newMat[i, y+col1] = Mat2[i, y]; 
     } 
    } 
    return newMat; 
} 
+2

這是功課?如果是,請使用[作業]標籤。 –

+0

@亨克霍爾特曼。不,我試圖讓自己的矩陣庫 – Shahgee

+0

記住檢查'row1 == row2'。 –

回答

2

移動數組時,您應該查看Array.CopyTo而不是逐個移動單元格。

此外,您可以創建一個接受2個矩陣的類,並提供一個抽象級別,使其看起來像1矩陣,但只是將它們保持在底下。

例如M1 = 20x 30M2 = 25 x 30所以你有一個類似於'M1 + M2'的類M3,一個55×30的矩陣。

當有人要求M3[28, 23]時,這個班級將知道它應該重定向到M2[8, 23],因爲M1只有20個職位(28-20 = 8)。這樣你就不需要複製內存,這很貴。弄清楚如何將請求重新路由到正確的矩陣要便宜得多。顯然取決於事後訪問矩陣的多少。

編輯 這就是我的意思是:

class Program { 
    static void Main(string[] args) { 

     int[,] x = { { 1, 2, 3 }, { 4, 5, 6 } }; 
     int[,] y = { { 7, 8, 9 }, { 10, 11, 12 } }; 

     var xy = new StitchMatrix<int>(x, y); 

     Console.WriteLine("0,0=" + xy[0, 0]); // 1 
     Console.WriteLine("1,1=" + xy[1, 1]); // 5 
     Console.WriteLine("1,2=" + xy[1, 2]); // 6 
     Console.WriteLine("2,2=" + xy[2, 2]); // 9 
     Console.WriteLine("3,2=" + xy[3, 2]); // 12 
    } 
} 

class StitchMatrix<T> { 
    private T[][,] _matrices; 
    private int[] _lengths; 

    public StitchMatrix(params T[][,] matrices) { 
     // TODO: check they're all same size   
     _matrices = matrices; 

     // call uperbound once for speed 
     _lengths = _matrices.Select(m => m.GetUpperBound(0)).ToArray(); 
    } 

    public T this[int x, int y] { 
     get { 
      // find the right matrix 
      int iMatrix = 0; 
      while (_lengths[iMatrix] < x) { 
       x -= (_lengths[iMatrix] + 1); 
       iMatrix++; 
      } 
      // return value at cell 
      return _matrices[iMatrix][x, y]; 
     } 
    } 
} 

問候格特 - 揚

+0

我知道這種方法,正是我想問這個。我不能實現這個矩形雙數組。 – Shahgee

+0

我看到2d這是更難,你可以改爲鋸齒狀數組嗎?那麼它會更容易一些。 – gjvdkamp

+0

新增了將它們拼接在一起的示例,非常簡單。實際上,創建單個矩陣很難,我認爲..也許在不安全的代碼中,您假設矩陣的佈局? – gjvdkamp

3

則可以將循環合併到:

for (i = 0; i < row1; i++) 
{ 
    for (j = 0; j < col1; j++) 
     newMat[i, j] = Mat1[i, j]; 

    for (y = 0; y < col2; y++) 
     newMat[i, y+col1] = Mat2[i, y]; 
} 

也許使用指針代替,但庫會正確是最好的解決方案(第一測試中的表現!)。這樣你就不必自己做微觀優化。

有很多在這個線程提到的.NET庫的:Matrix Library for .NET

根據您的性能需求,你也可以考慮並行算法,並可能由http://innovatian.com/2010/03/parallel-matrix-multiplication-with-the-task-parallel-library-tpl/的啓發。再次,一個構建良好的庫可能已經有了並行算法。

相關問題