Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to Matrix

Tags:

c#

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)
{
}
like image 804
Graviton Avatar asked Oct 02 '10 10:10

Graviton


People also ask

Is an array a matrix in MATLAB?

While other programming languages mostly work with numbers one at a time, MATLAB® is designed to operate primarily on whole matrices and arrays. All MATLAB variables are multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used for linear algebra.

Is an array of arrays A matrix?

An array is a vector with one or more dimensions. A one-dimensional array can be considered a vector, and an array with two dimensions can be considered a matrix.

Is an array just a matrix?

Arrays are superset of matrices. Matrices are a subset, special case of array where dimensions is two. Limited set of collection-based operations.


1 Answers

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]);
            }
        }
    }
}
like image 51
Jon Skeet Avatar answered Oct 08 '22 17:10

Jon Skeet