3

How to get the number in C# from the same distribution as a function exprnd() in Matlab ?

  • you can call matlab function from c# read here http://stackoverflow.com/questions/5901664/calling-a-matlab-function-from-c-sharp or here http://www.mathworks.com/help/matlab/matlab_external/call-matlab-function-from-a-c-client.html – Elior Apr 14 '13 at 10:57

3 Answers3

3

Try something like:

static readonly Random randomNumberGenerator = new Random();

public static double ExpRnd(double mu)
{
    return -Math.Log(randomNumberGenerator.NextDouble()) * mu;
}

If you want the m×n matrix, use

public static double[,] ExpRnd(double mu, int m, int n)
{
    var arr = new double[m, n];
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
            arr[i, j] = ExpRnd(mu);
    }
    return arr;
}

Note: The System.Random class is not thread-safe. If you have more than one thread calling ExpRnd above, you must be more careful.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
2

This blog post might help you:

http://ericlippert.com/2012/02/21/generating-random-non-uniform-data/

If you know -- or can work out -- the quantile function of the distribution you want then you can transform the (roughly) uniform distribution you already have into the given distribution.

As I describe in my blog post, the quantile function is the inverse of the cumulative distribution, and the cumulative distribution is the area under the distribution. Since the distribution you want is e-x it should be easy to work out the integral and the inverse.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • That's also how my answer works. [Wikipedia](http://en.wikipedia.org/wiki/Exponential_distribution#Generating_exponential_variates) gives the quantile function as $F^{-1}(p)=-\ln (1-p)\mu$ and notes that the "one minus" part can be left out. – Jeppe Stig Nielsen Apr 14 '13 at 13:45
1

You can use some external signal processing library like meta.numerics

Under Meta.Numerics.Statistics.Distributions namespace, have a look at ExponentialDistribution class and the corresponding GetRandomValue(Random) method.

Nishanth
  • 6,932
  • 5
  • 26
  • 38