Anthony
Anthony

Reputation: 3793

Convert an object of object arrays into several double arrays in C#

The problem is extracting double arrays in a multidimensional object array which itself is kept in a one-dimensional object array that is contained in a variable of object type.

I am trying to use Matlab API in a C# program. The Matlab script returns values in Matlab's matrix form which is then returned to the C# program as an object variable described as above.

An example of the returned data is as follows. The returned variable is called result which contains a one-dimensional object array. The one-dimensional object array contains a 1x4 object array and each of the objects in the 1x4 array contains a double array.

-       result  {object[1]}
  -     [0] {object[1, 4]}
    +       [0, 0]  {double[500, 6]}
    +       [0, 1]  {double[500, 6]}
    +       [0, 2]  {double[500, 6]}
    +       [0, 3]  {double[500, 6]}

How do I extract these double arrays?


Update

To get you a clearer picture of the variable in question, you can run the following code.

object result;
var resultSub1 = new object[1];

double[,] data1 = {{0,0},{0,0}};
double[,] data2 = {{0,0},{0,0}};
double[,] data3 = {{0,0},{0,0}};
double[,] data4 = {{0,0},{0,0}};
object[,] resultSub2 = { { data1, data2, data3, data4 } };

resultSub1[0] = resultSub2;
result = resultSub1;

How do I extract data1, data2, data3 and data4?

Upvotes: 1

Views: 616

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70671

Based on your clarification, I believe this is the code you're looking for:

double[,] data1, data2, data3, data4;

object[] resultArray = (object[]) result;
object[,] dataArrays = (object[,]) resultArray[0];

data1 = (double[,]) dataArrays[0, 0];
data2 = (double[,]) dataArrays[0, 1];
data3 = (double[,]) dataArrays[0, 2];
data4 = (double[,]) dataArrays[0, 3];

It's just a matter of casting appropriately at each level of the data structure. First, cast to the single-dimensional, single-element array type that the result value actually is. Then, retrieve that array's single element, casting it to the two-dimensional, four-element array type that it actually is. Finally, retrieve each of the four elements, casting each to the two-dimensional array of double values that it actually is.

Upvotes: 1

Jason Faulkner
Jason Faulkner

Reputation: 6568

Is there a way to get those double arrays inside this object result.

var subArrays = result[0];

The above would create subArrays which has 4 indexes (the double arrays).

If you wanted to combine all the double arrays into a single array (i.e. combine the 4 separate arrays) then this should work:

var allValues = new List<double[][]>();
foreach var subArray in subArrays
{
    allValues.AddRange(subArray);
}
var allValuesArray = allValues.ToArray();

Upvotes: 0

Related Questions