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)
{
}
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.
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.
Arrays are superset of matrices. Matrices are a subset, special case of array where dimensions is two. Limited set of collection-based operations.
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]);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With