c# - 使用 Math.Net Numerics 和 C# 对两个向量的值进行数字相加

标签 c# math vector numerics math.net

我有两个向量,如下所示:

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

我基本上想要一个向量 vdX,其结果是将 vdA 的所有元素除以 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
      }

使用 MathNet.Numerics,我找不到执行此操作的函数。

在 C# 中,我编写了这段代码来执行此操作

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());

是否有其他选项可以使用 c# 中的 Math.Net Numerics 更快地完成此任务?

最佳答案

你基本上需要一个 cross join in Linq 。您可以编写一个扩展方法,这样它看起来就像是一个 Math.Net 方法:

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; })
                  );
        }
    }
}

用法:

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);

这并不是特别快。

关于c# - 使用 Math.Net Numerics 和 C# 对两个向量的值进行数字相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19535406/

相关文章:

javascript - 掷骰子脚本分布均匀吗? (使用 Math.random())

unity-game-engine - Mathf.Lerp 错过最终值

c++ - 向 std::vector 或 typedef 添加自定义方法

python - 合并/连接具有不同元素的数组

c# - 在编译时更改返回类型

c# - 如果对象元素根标记不存在,如何将 XML 反序列化为对象?

c# - System.Net.WebException:无法解析远程名称:

python - 获得一个数字的所有除数的最佳方法是什么?

c++ - 根据额外参数对 vector 进行排序

c# - 如何使用 FluentFTP 列出文件夹