Ndarrays of ndarrays

Suppose I have a 2d ndarray whose elements are 2d ndarrays themselves. Can the outer 2d array be considered as a 4d array? Conversely, can a 4d array be taken as 2d array of 2d arrays or a 3d array of 1d arrays? If not, can you give me an alternative which can?

Edit -
Besides the answer, here's something interesting.

Specifically, what do you mean by "Can it be considered"? Surely it can be considered one, but I don't think that's all you are interested in.

For example, if a function accepts a 4d ndarrray as an argument, can it take the above 2d ndarray as well?

If you mean the ndarray crate, then no, because Array is generic over the dimensionality, so Array<T, Ix4> and Array<Array<T, Ix2>, Ix2> are distinct types. You'll have to explicitly convert the contents of the arrays in this case, for example by concatenating the whole nested array-of-arrays into a single Vec and then using from_shape_vec() for creating the required 4D array.

1 Like

That was comprehensive. Is there an alternative which makes this possible? I don't really require things like matrix multiplications, but the following are very desired.

  1. Fast iteration (parallel iteration if it exists)
  2. 4d = 2d + 2d = 3d + 1d (unlike ndarrays)
  3. MaybeUninit is needed.

You could make your own Array4D trait and implement it for each of the types you want. Then be generic whenever you wish to accept such an array. One problem is that each subarray in an Array<Array<T, Ix2>, Ix2> may not be of the same size.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.