本文介绍了在Matlab中生成具有最大值,最小值和均值(平均值)的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成具有以下属性的随机数.

I need to generate random numbers with following properties.

  • 最小必须为1
  • 最大数量必须为9
  • 平均(平均值)为6.00(或其他数值)
  • 随机数只能是整数(正数)

例如,我尝试了几种语法,但是没有用

I have tried several syntaxes but nothing works, for example

r=1+8.*rand(100,1);

这给了我一个1到9之间的随机数,但它不是整数(例如5.607或4.391),每次我计算平均值时都会变化.

This gives me a random number between 1-9 but it's not an integer (for example 5.607 or 4.391) and each time I calculate the mean it varies.

推荐答案

这里是一种算法,该算法具有一个循环,可通过从a的一半重新生成随机数来达到所需的均值xmean(具有所需的精度xeps).根据当前迭代中的平均值将向量向量化到另一个.通过我的测试,它很快就达到了平均值.

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是您需要的输出.

这篇关于在Matlab中生成具有最大值,最小值和均值(平均值)的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 14:06