Generate a random number with max, min and mean (average) in Matlab

前端 未结 6 2033
别那么骄傲
别那么骄傲 2020-12-19 23:09

I need to generate random numbers with following properties.

  • Min must be 1
  • Max must be 9
  • Average (mean) is 6.00 (or something else)
6条回答
  •  臣服心动
    2020-12-19 23:49

    Here is an algorithm with a loop to reach a required mean xmean (with required precision xeps) by regenerating a random number from one half of a vector to another according to mean at current iteration. With my tests it reached the mean pretty quick.

    n = 100;
    xmean = 6;
    xmin = 1;
    xmax = 9;
    xeps = 0.01;
    x = randi([xmin xmax],n,1);
    while abs(xmean - mean(x)) >= xeps
        if xmean > mean(x)
            x(find(x < xmean,1)) = randi([xmean xmax]);
        elseif xmean < mean(x)
            x(find(x > xmean,1)) = randi([xmin xmean]);
        end
    end
    

    x is the output you need.

提交回复
热议问题