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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace ublas = boost::numeric::ublas;

int main()
{
    ublas::vector<double> 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.

1
2
3
4
5
6
7
8
9
// might want to template on the element type at least
std::vector<int> f(const std::vector<int>& v1, const std::vector<int>& v2)
{
    std::vector<int> r;
    for(int n: v1)
        std::transform(v2.begin(), v2.end(), back_inserter(r),
                  [=](int i){return n*i;}); // std::bind2nd(std::multiplies<int>(), n) if you're not up to date
    return r;
}

demo: http://liveworkspace.org/code/2iwv3g$0
Last edited on
closed account (D80DSL3A)
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.
1
2
3
4
5
6
7
vector<double> M(n*n);
vector<double> a(n), b(n);
// provide values for the a[i] and b[i]
// calculate the product
for(int i=0; i<n; ++i)
    for(int j=0; j<n; ++j)
         M[i*n+j] = a[i]*b[j];// formula for each element 

EDIT: added comments.
Also, look into Cubbis solution methods for more general problems, or if you have trouble writing code like line 7 above.
Last edited on
Topic archived. No new replies allowed.