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

[SOLVED] Weird bug in replicate()

Tags: None
(comma "," separated)
User avatar
marton
Registered Member
Posts
10
Karma
0
OS

[SOLVED] Weird bug in replicate()

Wed May 27, 2009 5:49 pm
hi,

i found something strange. i'll let the code speak for itself:

Code: Select all

#include
#include

int main(int, char *[])
{
    Eigen::MatrixXf x(2,5);
    x << 9,8,7,6,5,
         4,3,2,1,0;
   
    x.cwise() /= x.col(0).rowwise().replicate(x.cols());
    std::cout << "bad: " << x << std::endl;


    Eigen::MatrixXf y(2,5), z;
    y << 9,8,7,6,5,
         4,3,2,1,0;

    z = y.col(0).rowwise().replicate(y.cols());
    y.cwise() /= z;
    std::cout << "good: " << y << std::endl;

    return 0;
}



output is:
bad: 1 8 7 6 5
1 3 2 1 0
good: 1 0.8889 0.7778 0.6667 0.5556
1 0.75 0.5 0.25 0

Seems like cwise() doesn't take into account the replicated data.

Cheers,
Marton

Last edited by ggael on Fri May 29, 2009 6:34 am, edited 1 time in total.
User avatar
marton
Registered Member
Posts
10
Karma
0
OS

RE: Weird bug in replicate()

Thu May 28, 2009 2:02 pm
Never mind, I wrote a description of the bug in bitbucket's issue tracker. Maybe an admin can even delete this thread?
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

RE: Weird bug in replicate()

Fri May 29, 2009 6:31 am
I answer here because this is not a bug and might be interesting for others.
Actually, this is an aliasing issue due to expression templates. Here x.col(0) return a reference to the first column element of x. When you write:

Code: Select all
x.cwise() /= x.col(0).rowwise().replicate(x.cols());


the values of x.col(0) are modified during the evaluation... This is equivalent to:

Code: Select all
for (int i=0;i<x.cols();++i)
  x.col(i).cwise() /= x.col(0);


The best solution is to copy x.col(0) to a temporary using .eval():

Code: Select all
x.cwise() /= x.col(0).eval().rowwise().replicate(x.cols());
User avatar
marton
Registered Member
Posts
10
Karma
0
OS

RE: Weird bug in replicate()

Fri May 29, 2009 6:44 am
Doh! Maybe I should have thought first.
Thanks, Gael, for the prompt answer!


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Sogou [Bot]