使用mathdotnet的Matlab等效函数

时间:2015-09-03 17:40:55

标签: c# matlab mathdotnet mathnet

我们如何使用math.net库在C#中实现下面的matlab函数。

多变量正态随机分布 - http://in.mathworks.com/help/stats/mvnrnd.html

r = mvnrnd(MU,SIGMA,cases)

同样在math.net函数下面没有返回任何结果。我已经尝试过其他方法,比如Selectpermutations / SelectVariations有/无重复。但是没有一个方法返回任何resuts。

IEnumerable<double> input=new double[] { 1, 2, 3, 4, 5 };
var re = input.SelectCombinationWithRepetition(3);

enter image description here

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

据我所知,没有现成的函数可以在Math.net中为您提供多元随机正态数。但是,您可以轻松地为此目的编写特定函数,该函数使用协方差矩阵的Cholesky分解。实际上,当p-变量向量Z的每个元素根据标准正态分布N(0,1)独立分布时,向量X = M + L * Z根据p-变量正态分布分布,其总体均值向量为M且其协方差矩阵为S(其中S = L * L&#39;)。

由于我是一名vb人,我将在此处显示用于编写此类函数的vb代码:

Public Function MvNRnd(Mu As Vector, Covariance As Matrix, Cases As Double) As Matrix

        Dim standardNormalDistribution As New Normal(0, 1)
        Dim randomValues(Cases - 1) As Vector
        Dim cholesky As Factorization.Cholesky(Of Double) = Covariance.Cholesky


        For i As Integer = 0 To Cases - 1

            'generate independent standard normal random numbers
            randomValues(i) = DenseVector.CreateRandom(Mu.Count, standardNormalDistribution)

            'generate multivariate normal random numbers
            cholesky.Factor.Multiply(randomValues(i), randomValues(i))
            randomValues(i) += Mu

        Next


        Return DenseMatrix.OfRowVectors(randomValues)

    End Function

等效的C#代码应如下所示(通过http://converter.telerik.com翻译):

public Matrix MvNRnd(Vector Mu, Matrix Covariance, double Cases)
{

    Normal standardNormalDistribution = new Normal(0, 1);
    Vector[] randomValues = new Vector[Cases];
    Factorization.Cholesky<double> cholesky = Covariance.Cholesky;



    for (int i = 0; i <= Cases - 1; i++) {
        //generate independent standard normal random numbers
        randomValues(i) = DenseVector.CreateRandom(Mu.Count, standardNormalDistribution);

        //generate multivariate normal random numbers
        cholesky.Factor.Multiply(randomValues(i), randomValues(i));
        randomValues(i) += Mu;

    }


    return DenseMatrix.OfRowVectors(randomValues);

}

答案 1 :(得分:1)

Random randomSource = new SystemRandomSource();

var mu = new DenseMatrix(2, 1, new[] { 2.0, 3 });
var sigma = new DenseMatrix(2, 2, new[] { 1, 1.5, 1.5, 3 });
var one = DenseMatrix.CreateIdentity(1);

var mvnrnd = new MatrixNormal(mu, sigma, one, randomSource);
var sample = mvnrnd.Sample();