tensormojolang

How to statically declare a Tensor?


I started exploring the mojo programming language and now I am trying to figure out how to properly use the Tensor module. I can't find how to statically declare the values inside a tensor.

For the moment, this is what I do to fill a tensor with values:

let dim1 = 2
let dim2 = 3

var matrice1 = Tensor[DType.float32](dim1, dim2)
for i in range(dim1):
    for j in range(dim2):
        matrice1[Index(i,j)] = 1

But I am looking for a way to do something like this:

var matrice1 = Tensor[DType.float32](dim1, dim2)
matrice1 = [[1, 2, 3],[1, 2, 3]]

Solution

  • You can initialize a Tensor from a literal like this:

    let dim1 = 2
    let dim2 = 3
    
    let tensor = Tensor[DType.float32](
        TensorShape(dim1, dim2),
        1, 2, 3,
        1, 2, 3
    )
    
    print(tensor)