2011-10-10 62 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/的启发。再次,一个构建良好的库可能已经有了并行算法。

相关问题