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):
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
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;
}
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.