Random numbers that add to 100: Matlab

前端 未结 4 1855
死守一世寂寞
死守一世寂寞 2020-11-22 07:25

[I\'m splitting a population number into different matrices and want to test my code using random numbers for now.]

Quick question guys and thanks for your help in a

4条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 08:09

    It is not too late to give the right answer

    Let's talk about sampling X1...XN in the range [0...1] such that Sum(X1, ..., XN) is equal to 1. Then you could rescale it to 100

    This is called Dirichlet distribution, and below is the code to sample from it. Simplest case is when all parameters are equal to 1, then all marginal distributions for X1, ..., XN would be U(0,1). In general case, with parameters different from 1s, marginal distributions might have peaks.

    ----------------- taken from here ---------------------

    The Dirichlet is a vector of unit-scale gamma random variables, normalized by their sum. So, with no error checking, this will get you that:

    a = [1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0]; // 9 numbers to sample
    n = 10000;
    r = drchrnd(a,n)
    
    function r = drchrnd(a,n)
      p = length(a);
      r = gamrnd(repmat(a,n,1),1,n,p);
      r = r ./ repmat(sum(r,2),1,p);
    

提交回复
热议问题