【问题标题】:Finding the average of Vectors in a list查找列表中向量的平均值
【发布时间】:2015-10-16 12:34:17
【问题描述】:

我有一个 Vector3 列表,每个都有 x、y、z 值。

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

我想遍历这个列表,找到平均值并从中创建一个向量:

结果向量:

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;

我正在尝试为此创建一个函数,希望得到您的帮助!

【问题讨论】:

    标签: c# list unity3d


    【解决方案1】:

    您可以使用 linq Enumerable.Average 来实现这一目标

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

    list.Average(x=&gt;x.Z) 将从list 的所有元素中返回Z 的平均值

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这可行,但是我使用了以前的答案。谢谢,我都试过了,效果很好。不确定两者的效率,但会检查 =)
      • @Passy 这将只通过列表一次,而对于 wudzik 的回答则为 3。无论哪种方式,两者在技术上都是线性的,而且 wudzik 的可能更容易阅读。
      • @rostok,这个参数根本不需要。
      猜你喜欢
      • 2014-08-20
      • 2012-02-20
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2020-08-10
      • 2016-07-24
      相关资源
      最近更新 更多