This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Passing row/cols to functions

Tags: None
(comma "," separated)
mlohry
Registered Member
Posts
8
Karma
0

Passing row/cols to functions

Thu May 15, 2014 10:14 pm
Code: Select all
#include <iostream>
#include <eigen3/Eigen/Core>

using namespace Eigen;
using namespace std;

template<typename MatrixType>
void AlterElement( MatrixType x ){
  x(0) = -1;
}

template<typename MatrixType>
void AlterElement2( MatrixType& x ){
  x(0) = -2;
}

int main(){

  Matrix<double,3,2> m;
  m *= 0;
  cout << m << endl;

  AlterElement(m.row(0));
  cout << m << endl;

  //  AlterElement2(m.row(1)); // won't compile, "expects l-value"
  auto r = m.row(1);
  AlterElement2(r);
  cout << m << endl;
}


In the previous code, I can pass the row "by value" -- does this actually make a copy of the block reference? In the second chunk, I'm trying to pass "by reference" but it fails to compile, unless I first set a variable to the row(). Two questions:

  • What is the appropriate way to pass a row with modifiable elements with minimal overhead?
  • What concrete class should be used here to avoid using templates?
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
mlohry
Registered Member
Posts
8
Karma
0

Re: Passing row/cols to functions

Fri May 16, 2014 1:37 pm
ggael wrote:Have a look at the Ref<> class: http://eigen.tuxfamily.org/dox/classEigen_1_1Ref.html


Near as I can tell, this will only allow you to send a const row to a function. I need to be able to modify the elements within the function. The "cast away constness" trick seen elsewhere seems like it gets away from this, but surely there must be a less hack-ish way?
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Passing row/cols to functions

Fri May 16, 2014 3:36 pm
nope, a Ref can be in/out as in the example of the doc. For instance, to accept a matrix, or any kind of submatrices including rows/columns:

Code: Select all
void foo1(Ref<MatrixXf> x);
mlohry
Registered Member
Posts
8
Karma
0

Re: Passing row/cols to functions

Fri May 16, 2014 5:47 pm
ggael wrote:nope, a Ref can be in/out as in the example of the doc. For instance, to accept a matrix, or any kind of submatrices including rows/columns:

Code: Select all
void foo1(Ref<MatrixXf> x);



The problem with that is that I can't access individual elements:

Code: Select all
void AlterElement3( Ref<MatrixXd> x){
  x(0) = -3;
}


Gives the static assertion "YOU_ARE_TRYING_TO_USE_AN_INDEX_BASED_ACCESSOR_ON_AN_EXPRESSION_THAT_DOES_NOT_SUPPORT_THAT"
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Passing row/cols to functions

Sat May 17, 2014 12:02 am
x(0,0) will do, but If you are expecting a vector, then do as in the doc:
Code: Select all
void foo1(Ref<VectorXf,0,Stride<> > x);


Stride<> is needed to accept a row of a column major matrix.


Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot], rblackwell