How to define the type of a 3X3X3 tensor

In physics you have a tensor which is 27 numbers organized in a cube with size 3 ie. 3X3X3.
How do you define a 3X3X3 tensor type ?
I think it’s something like an array of length 3 of an array of length 3 of an array of length 3…
type mytensor = ???

I see, the type is probably,

type mytensor= int array array array

Except if you use Array.unsafe_get when you will access elements in the arrays there will be a bound check. You can avoid this by using a record. The record field names can contain the indices like in tensor.m213.
I saw some ocaml libs doing so with matrices computations.

If you don’t mind using owl or owl-base, you can use its ndarray module to define and manipulate generic tensors: N-Dimensional Arrays - Owl Online Tutorials

E.g., modulo typos for doing it by memory, Owl.Dense.Ndarray.Generic.zeros Bigarray.Float64 [|3;3;3|] should define 3x3x3 tensor of double precision real numbers initialised with 0s.


The drawback of a record is you can not easily iterate over the fields.
opam install owl failed on compiling eigen, must check this …

owl-base is easier to install than owl due to issues with default Debian packages, and gives you the functionality you need for iteration, slicing etc. If you don’t need advanced mathematical functions, I recommend using it instead.

1 Like