-
Notifications
You must be signed in to change notification settings - Fork 71
Tensor construction and initialisation
Roman edited this page Oct 1, 2023
·
5 revisions
-
Tensor Constructors
- Initializer list constructors
- Constructing Tensors from a scalar
- Constructing Tensors from C arrays
- Constructing from std::array/std::vector
- Initialiser methods
There are many ways to construct Fastor tensors. The easiest way is using initializer lists or braces
Tensor<double,2,3> mat = {{1,2,3},
{4,5,6}};
You can create tensors of any order using braces for instances for a 3D tensor you do
Tensor<double,2,2,3> array_3d = {{{1,2,3},
{4,5,6}},
{{8,9,10},
{11,12,13}}};
Note the number of opening and closing braces should match the dimension (rank) of the tensor.
You can initialise all values of a tensor to a given scalar if you want
Tensor<int,4,4> a(5);
Tensor<float,2,2> b(0.f);
If you already have data stored in a C array or a pointer you can initialise your tensor as
double c_array[4] = {1,2,3,4};
Tensor<double,4> a(c_array); // construct a vector from c_array
Tensor<double,2,2> a(c_array); // construct a matrix from c_array
You can also construct a tensor from a std::array or std::vector
std::array<double,4> std_array = {1,2,3,4};
Tensor<double,2,2> a(std_array); // construct a matrix from std::array
std::vector<double> std_vec = {1,2,3,4};
Tensor<double,2,2> a(std_vec); // construct a matrix from std::vector
Note that you don't have to give the size as the size and dimension of the tensor is encoded in the type of the tensor
There are many initialiser methods provided that you can use for filling your tensors
Tensor<float,3,4,5> a;
a.zeros(); // fill all the elements with zero
a.ones(); // fill all the elements with one
a.fill(2.5); // fill all the elements with 2.5
a.random(); // fill all the elements with random numbers
a.iota(3); // fill all the elements with sequentially ascending number starting from 3
a.arange(3); // fill all the elements with sequentially ascending number starting from 3. Same as above