I am interfacing some code with raw pointers. So I have extensive use of the map class:
void foo(T* raw_pointer){
const int rows = ...;
const int cols = ...;
Map<Matrix<T, rows, cols>> mat(raw_pointer);
// DO some stuff with "mat"
}
Now I want to apply some cwise operations in foo
, which I accomplish using .array()
. The code works, however, it looks very messy due to all of the .array()
calls strewn in the function. For instance, for the sake of argument, let's suppose that the function looked like this:
void foo(T* raw_pointer){
const int rows = ...;
const int cols = ...;
Map<Matrix<T, rows, cols>> mat(raw_pointer);
for (int i = 0 ; i < 1000 ; ++i)
... something = i * mat.row(1).array() * sin(mat.row(4).array()) + mat.col(1).array();
}
Part of the problem with this is that it is very unclear what the code is actually doing. It would be much nicer if gave the variables names:
void foo(T* raw_pointer){
const int rows = ...;
const int cols = ...;
Map<Matrix<T, rows, cols>> mat(raw_pointer);
Matrix<T, 1, cols> thrust = mat.row(1);
Matrix<T, 1, cols> psi = mat.row(4);
Matrix<T, 1, cols> bias = mat.row(2);
for (int i = 0 ; i < 1000 ; ++i)
... something = i * thrust.array() * sin(psi.array()) + bias.array();
}
But it would be even nicer if I could get directly get a reference to the ArrayWrapper
s so that we aren't making any copies. However, the only way I can figure out how to get that to work is by using auto
:
void foo(T* raw_pointer){
const int rows = ...;
const int cols = ...;
Map<Matrix<T, rows, cols>> mat(raw_pointer);
auto thrust = mat.row(1).array();
auto psi = mat.row(4).array();
auto bias = mat.row(2).array();
for (int i = 0 ; i < 1000 ; ++i)
... something = i * thrust * sin(psi) + bias;
}
This code works, and upon testing appears to reference the entries in the pointer (as opposed to making copies like in the previous snippet). However, I am concerned about its efficiency since the Eigen documentation explicitly suggests NOT doing this. So could somebody please what the preferred way to define the types for the variables is in such a circumstance?
It seems to me like I should be using a Ref
here, but I can't figure out how to get that to work. Specifically, I have tried replacing auto
with
Eigen::Ref<Eigen::Array<T, 1, cols>>
and
Eigen::Ref<Eigen::ArrayWrapper<Eigen::Matrix<T, 1, cols>>>
but the compiler doesn't like either of those.