Search code examples
c#mathvectornumericsmath.net

add numerically the values of two vectors using Math.Net Numerics with C#


I have two vectors like the following:

vdA = { 8.0, 7.0, 6.0 }
vdB = { 0.0, 1.0, 2.0, 3.0 }

I basicly want a vector vdX that result is to sum all element of vdA by all values of vdB.

vdX = {
        8.0, 9.0, 10.0 11.0,
        7.0, 8.0, 9.0, 10.0,
        6.0, 7.0, 8.0, 9.0
      }

With MathNet.Numerics I couldn't find an function to do this.

In C# I make this code to do this

Vector<double> vdA = new DenseVector(new[] { 8.0, 7.0, 6.0 });
Vector<double> vdB = new DenseVector(new[] { 0.0, 1.0, 2.0, 3.0 });

List<double> resultSumVector = new List<double>();
foreach (double vectorValueA in vdA.Enumerate())
   foreach (double vectorValueB in vdB.Enumerate())
      resultSumVector.Add(vectorValueA + vectorValueB);
Vector<double> vdX = new DenseVector(resultSumVector.ToArray());

Are there any other options to accomplish this faster with Math.Net Numerics in c#?


Solution

  • You basically need a cross join in Linq. You can write an extension method, this way it looks like it is a Math.Net method:

    namespace MathNet.Numerics
    {
        public static class DenseVectorExtensions
        {
            public static DenseVector AddAlls(this DenseVector vdA, DenseVector vdB)
            {
               return DenseVector.OfEnumerable(
                         vdA.SelectMany(x => vdB, (y, z) => { return y + z; })
                      );
            }
        }
    }
    

    Usage :

    var vdA = new DenseVector(new[] { 8.0, 7.0, 6.0 });
    var vdB = new DenseVector(new[] { 0.0, 1.0, 2.0, 3.0 });
    var vdX = vdA.AddAlls(vdB);
    

    This is not particularly faster.