2015-09-03 93 views
2

我們如何在C#中使用math.net庫實現matlab下面的函數。Matlab等價函數使用mathdotnet

多元正態隨機分佈 - http://in.mathworks.com/help/stats/mvnrnd.html

r = mvnrnd(MU,SIGMA,cases) 

而且下面math.net功能沒有返回任何結果。我已經嘗試了其他方法,如Selectpermutations/SelectVariations,但沒有任何方法返回任何結果。

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

enter image description here

我錯過了什麼?

回答

1

據我所知,沒有現成的函數可以給你Math.net中的多元隨機正態數。但是,您可以輕鬆地編寫一個特定的函數來使用協方差矩陣的Cholesky分解。實際上,當p-變量向量Z的每個元素根據標準正態分佈N(0,1)獨立分佈時,向量X = M + L * Z根據其總體均值向量爲M的p-變量正態分佈來分佈並且其協方差矩陣是S(其中S = L * L')。

因爲我是一個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
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(); 
+0

您可以添加解決方案的解釋嗎? – Kmeixner

+0

該解決方案使用Math.net庫(http://www.mathdotnet.com/),它具有多元隨機正態數字函數(http://numerics.mathdotnet.com/api/mathnet.numerics.distributions/ matrixnormal.htm)。 Mu和Sigma的定義是在此線程原始問題中引用的Mathworks頁面(http://in.mathworks.com/help/stats/mvnrnd.html)中。 – porsove