Graviton
Graviton

Reputation: 83254

Convert Array to Matrix

I have an array of the length m*n, that stores a list of double element.

How to convert it into a matrix of m*n?

This is the method signature.

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

Upvotes: 8

Views: 16424

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500285

You can use Buffer.BlockCopy to do this very efficiently:

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

Upvotes: 14

Guffa
Guffa

Reputation: 700272

Create the matrix and loop the items into it:

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

Upvotes: 3

Eugene Cheverda
Eugene Cheverda

Reputation: 8930

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

Upvotes: 4

Related Questions