我有一个长度为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)
{
}
答案 0 :(得分: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]);
}
}
}
}
答案 1 :(得分: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 :(得分:2)
创建矩阵并将项目循环到其中:
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;
}