【问题标题】:How to make MATLAB's corrcoef (correlation coefficient) in C#?如何在C#中制作MATLAB的corrcoef(相关系数)?
【发布时间】:2015-11-09 23:59:55
【问题描述】:

我有一个列表,其中包含许多样本,代表来自嘈杂正弦波的许多幅度值。 我需要找到该波和给定正弦波(无噪声)的皮尔逊相关系数。 (所以我可以从嘈杂的波中找到正确的谐波)。 我真正需要的是在 C# 中的方法中执行相同的过程。 我知道这可以通过 MATLAB 中的 corrcoef 命令来完成。 非常欢迎任何解释或想法。 提前致谢。

【问题讨论】:

标签: c# matlab


【解决方案1】:

你为什么不用Math.NET Numerics

Math.NET Numerics 旨在为数值计算提供方法和算法 科学、工程和日常使用中的计算。涵盖的主题 包括特殊函数、线性代数、概率模型、随机 数字,插值,积分,回归,优化问题 等等。

您正在寻找的class 编码如下:

namespace MathNet.Numerics.Statistics
{
    using System;
    using System.Collections.Generic;
    using Properties;

    /// <summary>
    /// A class with correlation measures between two datasets.
    /// </summary>
    public static class Correlation
    {
        /// <summary>
        /// Computes the Pearson product-moment correlation coefficient.
        /// </summary>
        /// <param name="dataA">Sample data A.</param>
        /// <param name="dataB">Sample data B.</param>
        /// <returns>The Pearson product-moment correlation coefficient.</returns>
        public static double Pearson(IEnumerable<double> dataA, IEnumerable<double> dataB)
        {
            int n = 0;
            double r = 0.0;
            double meanA = dataA.Mean();
            double meanB = dataB.Mean();
            double sdevA = dataA.StandardDeviation();
            double sdevB = dataB.StandardDeviation();

            IEnumerator<double> ieA = dataA.GetEnumerator();
            IEnumerator<double> ieB = dataB.GetEnumerator();

            while (ieA.MoveNext())
            {
                if (ieB.MoveNext() == false)
                {
                    throw new ArgumentOutOfRangeException("Datasets dataA and dataB need to have the same length.");
                }

                n++;
                r += (ieA.Current - meanA) * (ieB.Current - meanB) / (sdevA * sdevB);
            }
            if (ieB.MoveNext() == true)
            {
                throw new ArgumentOutOfRangeException("Datasets dataA and dataB need to have the same length.");
            }

            return r / (n - 1);
        }
    }
}


Math.NET Numerics works very well with C# and related .Net languages. When using Visual Studio or another IDE with built-in NuGet support, you can get started quickly by adding a reference to the MathNet.Numerics NuGet package. Alternatively you can grab that package with the command line tool with nuget.exe install MathNet.Numerics -Pre or simply download the Zip package.

我大量使用了这个库,效果很好。所以你会像这样使用它:

using MathNet.Numerics.Statistics;

correlation = Correlation.Pearson(arrayOfDoubles1, arrayOfDoubles2);

【讨论】:

  • 它似乎对我来说很辛苦,我想自己做,但没关系,现在我只需要自己脱粒。非常感谢先生。
猜你喜欢
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
相关资源
最近更新 更多