Cross Product using Math.Net Numerics with C#

Sait picture Sait · Aug 1, 2012 · Viewed 9.9k times · Source

I have two vectors MathNet.Numerics.LinearAlgebra.Generic.Vector<double>, like the following:

Vector<double> v1 = new DenseVector(new double[] { 1, 2, 3 });     
Vector<double> v2 = new DenseVector(new double[] { 3, 2, 1 });

I basicly want to CrossProduct them, however couldn't find an official function. I know cross product is a very easy function which I can write myself, but I want to use the API's function.

Both of the below works for me: (Couldn't find such functions in the API.)

Vector<double> result = v1.CrossProduct(v2);
Vector<double> result = Vector.CrossProduct(v1,v2);

I found this, however couldn't find the function when I tried to write it: API Reference

Answer

denver picture denver · Nov 16, 2013

Sample method to do the cross-product of a 3 element vector.

    using DLA = MathNet.Numerics.LinearAlgebra.Double;

    public static DLA.Vector Cross(DLA.Vector left, DLA.Vector right)
    {
        if ((left.Count != 3 || right.Count != 3))
        {
            string message = "Vectors must have a length of 3.";
            throw new Exception(message);
        }
        DLA.Vector result = new DLA.DenseVector(3);
        result[0] = left[1] * right[2] - left[2] * right[1];
        result[1] = -left[0] * right[2] + left[2] * right[0];
        result[2] = left[0] * right[1] - left[1] * right[0];

        return result;
    }