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

Broadcasting + Multiply

Tags: broadcasting broadcasting broadcasting
(comma "," separated)
MMU
Registered Member
Posts
10
Karma
0

Broadcasting + Multiply

Mon Nov 28, 2011 8:45 pm
Greetings,

Making sure I am not crazy here, but using broadcasting you can add a column or row vector to each column or row in a matrix (or array) doing something like:

Code: Select all
ArrayXXd m(2,2);
m(0,0) = 5;
m(1,0) = 4;
m(0,1) = 3;
m(1,1) = 2;

RowVector2d v;
v << 2,3;
   
m=m.rowwise()+v.array();

(Please excuse code inefficiencies, I am just trying to get this to work).

You can also subtract in the same manner. However, am I correct in that you cannot multiply like this? I.E. replace the last line with m=m.rowwise()*v.array(). If I try this I get a compile error and I can't figure out a way to replicate the addition/subtraction broadcasting result with multiplication in order to multiply a column or row vector to each column or row in a matrix.

Any help would be appreciated. Thanks.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Broadcasting + Multiply

Tue Nov 29, 2011 11:53 am
This has been recently added in the default branch. Meanwhile you can express it a diagonal matrix product:

m = v.asDiagonal() * m.matrix();
MMU
Registered Member
Posts
10
Karma
0

Re: Broadcasting + Multiply

Tue Nov 29, 2011 1:07 pm
Awesome, thanks!
MMU
Registered Member
Posts
10
Karma
0

Re: Broadcasting + Multiply

Thu Dec 01, 2011 2:45 pm
Hi, sorry to reopen this old topic but m = v.asDiagonal() * m.matrix(); did not give the result I was expecting.

Example:
Code: Select all
ArrayXXd m(4,4);
m << 1, 2, 3, 4,
     5, 6, 7, 8,
     9, 10, 11, 12,
     13, 14, 15, 16;

RowVectorXd v(4);
v << 4, 3, 2, 1;
   
cout << m.rowwise()+v.array() << endl;
cout << v.asDiagonal()*m.matrix() << endl;


the first cout line gives:
Code: Select all
 
 5  5  5  5
 9  9  9  9
13 13 13 13
17 17 17 17


which is as expected, however the second cout line gives:
Code: Select all
 
 4  8 12 16
15 18 21 24
18 20 22 24
13 14 15 16


which is not the same functionality of m.rowwise()+v.array(). Replicating the same functionality of m.rowwise()+v.array() with multiplication should give me:
Code: Select all
 
 4  6  6  4
20 18 14  8
36 30 22 12
52 42 30 16


Is there any way to get this?
Thank you.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Broadcasting + Multiply  Topic is solved

Thu Dec 01, 2011 3:59 pm
to mimic a rowwise op do the product on the right:

m.matrix() * v.asDiagonal()
MMU
Registered Member
Posts
10
Karma
0

Re: Broadcasting + Multiply

Thu Dec 01, 2011 4:08 pm
Ah ok excellent, this worked. Thank you very much! (as you could tell, matrix math is not my forte :P)


Bookmarks



Who is online

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