This project has moved and is read-only. For the latest updates, please go here.

add several vectors

Sep 12, 2014 at 2:23 PM
Dear community,

I'd like to know how to add in a smart way several vectors, that is,

I have a List<double[]> lstVectors, and I want to all vectors in the array and have in return another double[]. Is there anything already implemented?

Thanks in advance,
Sep 19, 2014 at 7:22 PM
Edited Sep 19, 2014 at 7:30 PM
Assuming all of the "vectors" are the same length (if they aren't, then the result will be the same length as the shortest):
List<double[]> lstVectors = ...;
double[] vectorSum = lstVectors.Aggregate((a,b) => a.Zip(b, (aa, bb) => aa + bb).ToArray());
Not the most efficient, but it ought to do the job.

(For some reason the "plus" in the expression above is getting converted to the XML entity notation? But not in the editor Preview...)
Marked as answer by cdrnet on 9/21/2014 at 12:03 AM
Sep 21, 2014 at 8:03 AM
Edited Sep 21, 2014 at 8:04 AM
Alternatively, if the vectors are very large you could try whether the following is faster:
var result = new double[length];
foreach(var array in arrays)
    Control.LinearAlgebraProvider.AddArrays(array, result, result);
Of course, if the vectors were actual Math.NET Numerics vectors you could do:
var vectors = new List<Vector<double>>();
vectors.Aggregate((a, b) => a + b);
Marked as answer by cdrnet on 9/21/2014 at 12:03 AM