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

How to compute the Kronecker product

Tags: None
(comma "," separated)
fthomas
Registered Member
Posts
1
Karma
0
Hi,

What is the most efficient way to compute the Kronecker product of two matrices with Eigen? The code below does the job and seems straightforward for me, but maybe it is not the most efficient approach?

Code: Select all
MatrixXf m1(2, 2), m2(2, 2);
m1 << 1, 2, 3, 4;
m2 << 5, 6, 7, 8;
cout << m1 << endl << endl << m2 << endl << endl;

MatrixXf m3(m1.rows()*m2.rows(), m1.cols()*m2.cols());

for (int i = 0; i < m1.cols(); i++) {
  for (int j = 0; j < m1.rows(); j++) {
    m3.block(i*m2.rows(), j*m2.cols(), m2.rows(), m2.cols()) =  m1(i,j)*m2;
  }
}

cout << m3 << endl;


Thanks
Frank
User avatar
bjacob
Registered Member
Posts
658
Karma
3
Actually, your code is pretty good, it doesn't create an unneeded temporary, and I think that it allows eigen to vectorize (for large enough matrices). You might want to check by adding asm comments as explained in the Eigen FAQ.

Your code has also the merit of reading each entry of m1 only once. Entries of m2 are reread n^2 times but i don't know if there's much to do about it.

Remember, if your matrices have fixed size, it's always beneficial to use fixed-size matrix types and the fixed-size variants of block().

If your matrices are guaranteed to be of size nxn with n a multiple of 4, and not too big, then there is room for improvement if you can tell eigen that all packets are aligned so it doesn't need to care about unaligned boundaries.


Join us on Eigen's IRC channel: #eigen on irc.freenode.net
Have a serious interest in Eigen? Then join the mailing list!
Eclat
Registered Member
Posts
1
Karma
0
For those who may want use this code, there is some mistakes into the loops initializations.


Bookmarks



Who is online

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