More efficient way to do `Q.slice(a).col(b)` using Armadillo

Viewed 68

Is there a more efficient way to extract a column from a cube in Armadillo than Q.slice(a).col(b)?

Something like tube, but for the last 2 dimensions instead of the first 2.

1 Answers

Obtain a pointer to the first element of the desired column of the desired slice. Then pass that pointer to one of the advanced constructors of the vec class. Example:

cube C(6, 5, 4, fill::randu); // cube with 4 slices

vec v1 = C.slice(2).col(3);  // normal way of extracting a vector

vec v2( &C(0,3,2), C.n_rows, false, false);  // alternative way

Note that while this works, it's not safe. If C is resized or deleted, v2 will be using unallocated memory, or memory from a different object. In the first case it may result in a segfault. In the second case it's an information leak.

If C is a const cube, use const_cast to strip away the const from the obtained pointer. Again, this is not safe.

Related