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

Return expression by function

Tags: None
(comma "," separated)
matthiasw
Registered Member
Posts
6
Karma
0

Return expression by function

Tue Aug 25, 2015 8:51 pm
Hello,

I have a quite silly problem, which I can not solve. I have a 3xN Matrix (M) and a N RowVector (v) (I've chosen a RowVector to remove the transpose), where each column of the matrix should be multiplied with the corresponding coefficient of the vector.

My expression reads:
Code: Select all
M.array().rowwise() * v.array()
which returns an expression of the type
Code: Select all
Eigen::CwiseBinaryOp<
            Eigen::internal::scalar_product_op<double, double>,
            const Eigen::ArrayWrapper<const Eigen::Matrix<double, 3, -1> >,
            const Eigen::Replicate< Eigen::ArrayWrapper<const Eigen::Matrix<double, 1, -1> >, 3, 1 >
         >

However, when I put this expression as return type of a function I get a lot of invalid memory access from valgrind or std::bad_alloc.

I have a small sample program:
Code: Select all
#include <Eigen/Core>
#include <iostream>
static const Eigen::RowVectorXd v = Eigen::RowVectorXd::Random(5);
static const Eigen::Matrix<double, 3, -1> M = Eigen::MatrixXd::Random(3, 5);

typedef const Eigen::CwiseBinaryOp<
                                Eigen::internal::scalar_product_op<double, double>,
                                const Eigen::ArrayWrapper<const Eigen::Matrix<double, 3, -1> >,
                                const Eigen::Replicate< Eigen::ArrayWrapper<const Eigen::Matrix<double, 1, -1> >, 3, 1 >
                        > return_type;

return_type testf() {
        return M.array().rowwise() * v.array();
}

int main()  {
        // works fine
        Eigen::Matrix<double,3, -1> testvar = M.array().rowwise() * v.array();
        std::cout<<testvar<<std::endl;

        // following fails with or without .eval()
        Eigen::Matrix<double,3, -1> testvar2 = testf().eval();
        std::cout<<testvar2<<std::endl;
        return 0;
}


Do you have any sugguestions? Thank you in advance!

Matthias

PS: using Eigen 3.2
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Return expression by function

Tue Sep 01, 2015 8:09 am
This is probably because of the Vectorwise proxy object which is deleted too early. By passing the call to rowwise() should fix the issue. Anyway, a better and simpler expression is:

M * v.asDiagonal()

which returns a DiagonalProduct<Matrix<>,DiagonalWrapper<>,OnTheRight> expression in 3.2. In 3.3 it will return a generic Product<Matrix<>,DiagonalWrapper<>,LazyProduct>.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], q.ignora, watchstar