Search code examples
pythonc++eigeneigen3

Computing the outer product of two vectors in Eigen c++


I have a piece of python code written using numpy that I'm trying to port over to C++ using the eigen library. I haven't really found anything suitable in the eigen library.

This is the python equivalent:

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))

And What I've written using the Eigen Library is:

   Eigen::VectorXf u = Eigen::VectorXf::LinSpaced(100, 0, 2*PI);
   Eigen::VectorXf v = Eigen::VectorXf::LinSpaced(100, 0, PI);
   Eigen::MatrixXf x = u.cos().cross(v.cos());
   Eigen::MatrixXf y = u.sin().cross(v.sin());
   Eigen::MatrixXf z = Eigen::VectorXf::Ones(u.size()).cross(v);

Unfortunately, it looks like the cross function only works for vectors of size 3 as I get this error:

THIS_METHOD_IS_ONLY_FOR_VECTORS_OF_A_SPECIFIC_SIZE

and I'm trying to compute for a much larger size. I found this from a thread a while back but it doesn't seem that this functionality was implemented. Does anyone know how to achieve this?


Solution

  • To achieve the same behavior as np.outer(a, b), where a and b are both column vectors (i.e. VectorXf for instance) in Eigen it would simply be:

    a * b.transpose()
    

    For info, the thread you linked has nothing to do with the outer product. Rather, it's about the "exterior product" (I know the two names are confusingly similar to each other); this is also known as wedge product and it is basically an extension of the cross product to N-dimensional vectors. According to this definition, the exterior product of N dimensional vectors is a skew-symmetric NxN matrix with i,j-th entry equal, up to the sign, a[i]*b[j] - a[j]*b[i], while on the case of the outer product it would simply be a[i]*b[j]