简体   繁体   中英

Finding the average of Vectors in a list

I have a list of Vector3, each with x,y,z values.

List<Vector3> list = new List<Vector3>();

I would like to iterate through this list, and find the average and create a vector from it:

resultant vector:

averageVector.X = average of all the x values;
averageVector.Y= average of all the y values;
averageVector.Z = average of all the z values;

return averageVector;

I'm trying to create a function for this, and would love your help!

您可以使用Enumerable.Aggregate对向量求和,然后除以计数即可获得平均值。

var average = list.Aggregate(new Vector3(0,0,0), (s,v) => s + v) / (float)list.Count;

You can use linq Enumerable.Average to achive that

var newVector = new Vector3(
        list.Average(x=>x.X),
        list.Average(x=>x.Y),
        list.Average(x=>x.Z));

list.Average(x=>xZ) will return average value of Z from all elements from list

A modern code way to solve this is using a Unity Bounds axis-aligned bounding box.

Code looks like this:

var bounds = new Bounds(Vector3.zero, Vector3.zero);
list.ForEach(v => bounds.Encapsulate(v));
return bounds.center;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM