连接2D数组

我有两个数组mat1和Mat2。 我想要new_mat = [ma1,mat2]; 我写了一个有效的function。 我想知道是否有一个非常大的矩阵的有效函数或我如何使用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; } 

移动数组时,您应该查看Array.CopyTo,而不是逐个移动单元格。

你也可以创建一个接受2个矩阵的类,并提供一个抽象级别,使它们看起来像1个矩阵,但只是让它们分开。

例如, M1 = 20x 30M2 = 25 x 30因此你有一个M3级,看起来像’ M1 + M2 ,一个55 x 30矩阵。

当有人要求M3[28, 23]这个class级会知道它应该重定向到M2[8, 23] 8,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(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 { 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]; } } } 

关心Gert-Jan

您可以将循环组合成:

 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]; } 

也许可以使用指针(首先测试性能!)但是库可能是最好的解决方案。 这样您就不必自己进行微观优化。

这个post中提到了.Net的很多库: Matrix Library for .NET

根据您的性能要求,您还可以查看并行算法,您可能会受到http://innovatian.com/2010/03/parallel-matrix-multiplication-with-the-task-parallel-library-tpl/的启发。 同样,构建良好的库可能已经具有并行算法。