连接一个二维数组

3

我有两个数组mat1和mat2。 我想要一个新的数组new_mat=[mat1, 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
这是作业吗?如果是,请使用[作业]标签。 - H H
@Henk Holterman。不,我正在尝试制作自己的矩阵库。 - Shahgee
记得检查 row1 == row2 - Lasse Espeholt
2个回答

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 库:.NET 矩阵库

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


2
移动数组时,您应该查看Array.CopyTo,而不是逐个移动单元格。
此外,您可以创建一个接受2个矩阵的类,并提供一定程度的抽象,使它们看起来像一个矩阵,但在下面仍然保持分离状态。
例如,M1 = 20x30M2 = 25 x 30,因此您有一个类M3,'看起来像'M1 + M2,即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


我知道这个方法,而且我正想问这个问题。但是我无法在矩形双数组中实现它。 - Shahgee
我看到对于二维数组来说这更难了,你能否改成不规则数组呢?那样会再次变得容易些。 - gjvdkamp
添加了将它们拼接在一起的示例,这很容易。实际上创建一个单独的矩阵很难,我想也许可以使用不安全代码来假设矩阵的布局? - gjvdkamp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接