I have to use a method which accepts double[,], but I only have a double[]. How can I convert it?
Solution so far:
var array = new double[1, x.Length];
foreach (var i in Enumerable.Range(0, x.Length))
{
array[0, i] = x;
}
I have to use a method which accepts double[,], but I only have a double[]. How can I convert it?
Solution so far:
var array = new double[1, x.Length];
foreach (var i in Enumerable.Range(0, x.Length))
{
array[0, i] = x;
}
There's no direct way. You should copy stuff into a double[,]
. Assuming you want it in a single row:
double[,] arr = new double[1, original.Length];
for (int i = 0; i < original.Length; ++i)
arr[0, i] = original[i];
Mehrdad assumes that the width is one since there is no real way to determine either the width or height from a one dimensional array by itself. If you have some (outside) notion of the 'width' then Mehrdad's code becomes:
// assuming you have a variable with the 'width', pulled out of a rabbit's hat
int height = original.Length / width;
double[,] arr = new double[width, height];
int x = 0;
int y = 0;
for (int i = 0; i < original.Length; ++i)
{
arr[x, y] = original[i];
x++;
if (x == width)
{
x = 0;
y++;
}
}
Although, Row major is probably more common in many applications (matrices, text buffers or graphics):
// assuming you have a variable with the 'width', pulled out of a rabbit's hat
int height = original.Length / width;
double[,] arr = new double[height, width]; // note the swap
int x = 0;
int y = 0;
for (int i = 0; i < original.Length; ++i)
{
arr[y, x] = original[i]; // note the swap
x++;
if (x == width)
{
x = 0;
y++;
}
}
I just wrote this code which I will use:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace MiscellaneousUtilities
{
public static class Enumerable
{
public static T[,] ToRow<T>(this IEnumerable<T> target)
{
var array = target.ToArray();
var output = new T[1, array.Length];
foreach (var i in System.Linq.Enumerable.Range(0, array.Length))
{
output[0, i] = array[i];
}
return output;
}
public static T[,] ToColumn<T>(this IEnumerable<T> target)
{
var array = target.ToArray();
var output = new T[array.Length, 1];
foreach (var i in System.Linq.Enumerable.Range(0, array.Length))
{
output[i, 0] = array[i];
}
return output;
}
}
}