2010-10-02 36 views
7

que tienen una amplia gama de la longitud m*n, que almacena una lista de double elemento.Convertir matriz a Matrix

Cómo convertirla en una matriz de m*n?

Esta es la firma del método.

//returns a matrix of [m,n], given arr is of length m*n 
static double[,] ConvertMatrix(Array arr, int m, int n) 
{ 
} 
+2

Hhm usted tiene que saber, ya sea ' n' o 'm'. Una matriz con 16 elementos podría ser representado por '16 * 1',' 8 * 2', '4 * 4',' 2 * 8' y '1 * 16'. –

+1

¡Hah! ¡Una matriz ES una matriz! Buen chiste. –

+0

Sí, se conocen 'm' y' n'. Pregunta actualizada – Graviton

Respuesta

12

Puede utilizar Buffer.BlockCopy hacer esto de manera muy eficiente:

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]); 
      } 
     } 
    } 
} 
+0

Usando sizeof (doble) en lugar de llanura 8 apoyaría implementaciones donde el tipo doble tiene un tamaño diferente. No sé si existe tal bestia. Todavía. –

+4

@ Frédéric: En realidad está garantizada * * a ser de 8 por la especificación (véase la sección 18.5.8) - pero 'sizeof (...)' sería más explica por sí mismo de todos modos. –

4
private static T[,] create2DimArray<T>(T[] array, int n) 
     { 
      if (n <= 0) 
       throw new ArgumentException("Array N dimension cannot be less or equals zero","n"); 
      if (array == null) 
       throw new ArgumentNullException("array", "Array cannot be null"); 
      if (array.Length == 0) 
       throw new ArgumentException("Array cannot be empty", "array"); 

      int m = array.Length % n == 0 ? array.Length/n : array.Length/n + 1; 
      var newArr = new T[m,n]; 
      for (int i = 0; i < arr.Length; i++) 
      { 
       int k = i/n; 
       int l = i % n; 
       newArr[k, l] = array[i]; 
      } 

      return newArr; 
     } 
2

la matriz se crea y bucle los ítems en ella:

static double[,] ConvertMatrix(double[] arr, int m, int n) { 
    double[,] result = new double[m, n]; 
    for (int i = 0; i < arr.Length; i++) { 
    result[i % m, i/m] = arr[i]; 
    } 
    return result; 
}