-
Notifications
You must be signed in to change notification settings - Fork 71
Element access and indexing
Roman edited this page Jun 11, 2020
·
4 revisions
Tensor elements can be accessed individually using operator()
. Note that, while indexing tensors indices start from zero.
Tensor<float,3> vec = {3.5,6.7,8.2};
float vec_2 = vec(2); // the 3rd (last) element in the vector
// note that you can also get the last element as follows
float vec_last = vec(last); // or float vec_2 = vec(-1);
// note that you can get the first element as follows
float vec_first = vec(first); // or float vec_first = vec(0);
Tensor<float,2,3> mat = {{1,2,3},{4,5,6}};
float el_11 = mat(1,1); // element in first row and first column mat(1,1) = 5
// get the element in the first row and last column
float el_first_last = mat(first,last); // mat(first,last) = 3
Note that the number of arguments in operator()
should match the dimension of the tensor. That is, you can not index a 3D tensor with two indices
Tensor<double,3,3,3> a;
a(1,2,0); // fine
a(1,2); // will not compile
Assigning works in the same way as indexing but you just assign a number to a given element of a tensor
Tensor<float,3,3,3> a;
a(0,2,1) = -5.7; // assign -5.7 to element a(0,2,1) of the 3D tensor