Re: [eigen] How to return an Eigen matrix

[ Thread Index | Date Index | More lists.tuxfamily.org/eigen Archives ]


Hi,

The point is about C++ in general, not Eigen: you can't return a
reference to an object that is created in the stack of the function
(unless it's "static").

Just change func1 to accept the output matrix as an argument passed by
reference; also, read in the Eigen web about using MatrixBase<> for
function arguments, which is much more general than Matrix<>.

It should be like:

template <class Derived>
inline void func1(MatrixBase<Derived> &out_mat ){
  // Do something then return a matrix
  out_mat = ...
}

Cheers,
JL

On Sat, Oct 1, 2011 at 5:24 AM, Hung Dang <hungptit@xxxxxxxxx> wrote:
> Hi all,
>
>  I am new to Eigen so I am sorry for my naive question. I am trying to
> write a function which will return an Eigen template matrix (see code
> below). In my code func2 works fine, however, func1 does not. The g++
> compiler complain that there is no matching function for call to func1.
>
> What should I do to return an Eigen matrix?
>
> Thanks in advance
> Hung
>
> My test code:
>
> #include <iostream>
> #include <fstream>
> #include <string>
>
> #include "Eigen/Dense"
>
> using std::string;
> using std::cout;
> using std::endl;
> using namespace Eigen;
>
> template <class T>
> inline Matrix<T, Dynamic, Dynamic> & func1(){
>  // Do something then return a matrix
>  Matrix<T, 3, 5> A;
>  return A;
> }
>
> inline MatrixXd func2(){
>  // Do something then return a matrix
>  MatrixXd A(3,5);
>  return A;
> }
>
> int main (int nargc, char *argv[]){
>  string dataFileName = "dat.txt";
>
>  Matrix<double, Dynamic, Dynamic> A = func1();
>  cout << "Matrix A:" << endl << A << endl;
>
>  // MatrixXd B = func2();
>  // cout << "Matrix B:" << endl << B << endl;
>
>  return 0;
> }
>
>
>
>



-- 
___________________________________________________________

Dr. Jose-Luis Blanco-Claraco
Dpt. Ing. Civil, Mat. y Fabric - Phone: +34 951 952435
E.T.S.I. Industriales - Despacho 2.037
Universidad de Malaga - Campus Universitario de Teatinos
29071 Malaga, Spain
https://sites.google.com/site/jlblancosite/
___________________________________________________________



Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/