Redesign1991
Redesign1991

Reputation: 137

How to convert multidimensional array to jagged? (C#)

For a project I have a multidimensional array (double[,]) containing double values. Since I'm using a method from the accord framework that expects to receive a jagged array of doubles (double[][]) I need to convert one into the other. However, using the code below, I notice that I never reach the inputs[k] = row; statement.

double[][] inputs = new double[165][];

// Loop through # of rows
for (int k = 0; k < pcaComponents.GetLength(1); k++)
{
       double[] row = new double[20];

       // Loop through # of columns
       for (int l = 0; l < pcaComponents.GetLength(0); l++)
       {
            row[k] = pcaComponents[k, l];
       }
        inputs[k] = row;
}

pcaComponents is of type double[,] and is passed through from another piece of code. By using the getLength property I can see that when I'm passing 1, the result is 165, which is the # of rows and by passing 0 I can see that the result is 20, which is the # of columns. Then I try to create a new row for the jagged array with the values from the multidimensional array. It loops through the 2nd loop 20 times, but it doesn't seem to reach the inputs[k] = row; statement and doesn't continue the 1st loop where pcaComponents.GetLength(1) equals 165.

Upvotes: 1

Views: 736

Answers (1)

Fratyx
Fratyx

Reputation: 5797

I think you have to replace your line

row[k] = pcaComponents[k, l];

by that one

row[l] = pcaComponents[k, l];

The variable of your inner loop is l not k

And maybe you should use the GetLength for sizing your arrays:

double[] row = new double[pcaComponents.GetLength(0)];

Upvotes: 1

Related Questions