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

dividing rows of a matrix cwise by a vector

Tags: None
(comma "," separated)
GeorgeKnight
Registered Member
Posts
15
Karma
0
Hi,

I'm trying to divide each row of a matrix cwise with a vector. The following already does what I want:

MatrixXf m(4,4);
m << 1, 2, 3, 4,
5, 6, 7, 8,
9,10,11,12,
13,14,15,16;

VectorXf v(4);
v << 1,2,3,4;

for (int n = 0; n < m.cols(); ++n)
{
m.col(n) /= sqrt(v(n));
}


Is there a shorter way to accomplish this? I would think that a clever combination of rowwise() and v.array().sqrt().inverse() could do the trick, but the obvious

m.rowwise() *= v.array().sqrt().inverse();

does not compile because there is no viable *= operator defined.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
good point, we are missing some API in rowwise/colwise, however the API will be:

m.array().rowwise() *= v.array().sqrt().inverse();

because coeff-wise products are reserved for the array world.


forget what I said! Actually what you want is a diagonal matrix product:

m = m * (v.array().sqrt().inverse()).matrix().asDiagonal();
GeorgeKnight
Registered Member
Posts
15
Karma
0
That's clever indeed, thanks!

If I understand the docs well, Eigen optimizes for multiplication with diagonal matrices, so the solution above is also a fast one.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
yes it's as fast, and actually that's the reason why did not add such vector-wise operator * though you are far to be first one to first look for it... So either we add them, or we find a way to document it efficiently....


Bookmarks



Who is online

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