-7

I'm trying to declare this kind of variable:

float[][]

Things that didn't work for me (wouldn't compile) -

float[][] inputs = new float[10][5];
float[][] inputs = new float[10, 5];

When trying to declare the array like this -

int a = 3;
int b = 2;

float[][] inputs = new float[][]
{
   new float[a],
   new float[b]
};

I get a multidimensional array with two float arrays instead of an array that has 3 arrays and every array size is 2.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Shay Lugassy
  • 119
  • 1
  • 2
  • 6

1 Answers1

7

Well, there are two different types:

  • Array of array (jagged array):

    float[][] sample = new float[][] {
      new float[] {1, 2, 3},
      new float[] {4, 5}, // notice that lines are not necessary of the same length
    };
    
  • 2d array:

    float[,] sample2 = new float[,] {
      {1, 2, 3},
      {4, 5, 6},
    };
    

Edit: your code amended:

  // jagged array (10 arrays each of which has 5 items)
  float[][] inputs = new float[10][] {
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
  };

You can shorten the declaration with a help of Linq:

  float[][] inputs = Enumerable
    .Range(0, 10)               // 10 items
    .Select(i => new float[5])  // each of which is 5 items array of float
    .ToArray();                 // materialized as array

Or in case of 2d array

  // 2d array 10x5
  float[,] inputs = new float[10,5];
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Related [What are the differences between a multidimensional array and an array of arrays in C#?](http://stackoverflow.com/q/597720/579895) – Pikoh Mar 01 '17 at 09:16
  • is your (amended) initialization code more efficient then using a loop? E.g. `for (var idx = 0; idx < a; idx++) input[idx] = new float[b];`? – JHBonarius Mar 01 '17 at 09:40
  • @J.H.Bonarius: If *building* array is allowed then you can come up with a *loop* solution (as you've done), however, when *declaration* required, e.g. `private float[][] inputs = ?` you can't use loops. – Dmitry Bychenko Mar 01 '17 at 09:42
  • Could you elaborate on "building arrays"? I don't know the concept... I've been using the loop a lot in my code, and as its a high performance mathematical application, I would like to optimize. edit: maybe I should just ask a question in [cr] – JHBonarius Mar 01 '17 at 09:46
  • @:J.H.Bonarius you can't *declare* an array (say, a `field` within a class) with a help of loops: `private float[][] inputs = /* no loops here*/`. However, if you're allowed to declare the field as `float[][] inputs = new float[10][];` and only after that (in constructor) to build the array: `public MyClass() {/* you can use loops within a method/constructor */}` loop is a good solution. – Dmitry Bychenko Mar 01 '17 at 09:53