将数组转换为矩阵

Gra*_*ton 7 c#

我有一个长度数组m*n,存储一个double元素列表.

如何将其转换为矩阵m*n

这是方法签名.

//returns a matrix of [m,n], given arr is of length m*n
static double[,] ConvertMatrix(Array arr, int m, int n)
{
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

您可以Buffer.BlockCopy非常有效地使用它:

using System;

class Test
{
    static double[,] ConvertMatrix(double[] flat, int m, int n)
    {
        if (flat.Length != m * n)
        {
            throw new ArgumentException("Invalid length");
        }
        double[,] ret = new double[m, n];
        // BlockCopy uses byte lengths: a double is 8 bytes
        Buffer.BlockCopy(flat, 0, ret, 0, flat.Length * sizeof(double));
        return ret;
    }

    static void Main()
    {
        double[] d = { 2, 5, 3, 5, 1, 6 };

        double[,] matrix = ConvertMatrix(d, 3, 2);

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                Console.WriteLine("matrix[{0},{1}] = {2}", i, j, matrix[i, j]);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Frédéric:实际上*保证*在规范中是8(参见第18.5.8节) - 但是`sizeof(...)`无论如何都会更加自我解释. (4认同)