连接2D数组

时间:2011-10-10 09:58:21

标签: c# .net

我有两个阵列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 :(得分: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/的启发。同样,构建良好的库可能已经有并行算法。

答案 1 :(得分:2)

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

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

例如M1 = 20x 30M2 = 25 x 30所以你有一个类似于'M1 + M2的类M3,一个55 x 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];
        }
    }
}

关心Gert-Jan