You are using a version without Ads of this website. Please, consider donating:

### Kronecker (direct) vector product

Hi!

Does anybody know how to code the Kronecker/direct product of two vectors??

The direct product of the vectors a and b is given as the matrix below (note "x" refers to x with a circle around it and is the symbol for a Kronecker product):

(a1, a2,..., an) "x" (b1, b2,...,bn) = [a1b1, a1b2,..., a1bn]
[a2b1, a2b2,..., a2bn]
[ . . . . ]
[ . . . . ]
[ . . . . ]
[anb1, anb2,..., anbn]

The way I have coded the rest of the program is such that the matrix shown here is represented by a vector of length equivalent to the number of elements in the matrix. So I want the Kronecker product to give me a vector of length n^2 (where n is the number of elements in each initial vector).

Thanks, any help would be really appreciated.
Matt
Last edited on
The formatting is all off, but the product is a matrix n by n.
You could save yourself a lot of effort by using a matrix library. Pretty much every library, even the simple one included in boost, can do it:

 ``1234567891011121314`` ``````#include #include namespace ublas = boost::numeric::ublas; int main() { ublas::vector v1(3), v2(3); for (unsigned i = 0; i < 3; ++i) v1 (i) = i, v2 (i) = i*10; std::cout << v1 << '\n' << v2 << '\n' << outer_prod(v1, v2) << '\n'; }``````

demo: http://liveworkspace.org/code/fb4yz\$4

As for your requirements, it's a simple exercise in vector handling, which can be implemented in a number of ways.

 ``123456789`` ``````// might want to template on the element type at least std::vector f(const std::vector& v1, const std::vector& v2) { std::vector r; for(int n: v1) std::transform(v2.begin(), v2.end(), back_inserter(r), [=](int i){return n*i;}); // std::bind2nd(std::multiplies(), n) if you're not up to date return r; }``````

demo: http://liveworkspace.org/code/2iwv3g\$0
Last edited on
Another option is direct calculation, which seems practical because the formula is known and simple.
 So I want the Kronecker product to give me a vector of length n^2 (where n is the number of elements in each initial vector).

I assume that each n elements would represent a "row" in an nxn matrix, ie.
 ``1234567`` ``````vector M(n*n); vector a(n), b(n); // provide values for the a[i] and b[i] // calculate the product for(int i=0; i