生成较大的随机整数-MATLAB

时间:2018-11-10 00:48:32

标签: matlab random integer

尝试为x分配适当的值,这将导致1到60之间的随机整数。有什么建议吗?我做了randn,但是却越来越少。到目前为止,这是代码:

function s = Q11sub1(x)
    x =                 % <------ Question is what goes here
    if x <= 30      
        s = "small";       
    elseif x > 30 & x <= 50       
        s = "medium";  
    else    
        s = "high";  
    end
end

2 个答案:

答案 0 :(得分:2)

使用randi

randi(60)

这将为您提供1到60之间的伪随机整数。

参考:https://www.mathworks.com/help/matlab/ref/randi.html

答案 1 :(得分:2)

问题是npm install会生成遵循标准Normal distribution的随机数,例如正常(mu = 0,std = 1)。

正如@Banghua Zhao指出的那样,您想要randn函数,我将添加它们将在这些整数边界(称为discrete uniform distribution)之间的整数(包括两端)均匀分布。
代码randi将生成一个整数NxM矩阵,该矩阵均匀地分布在间隔[a,b]上,包括两端。呼叫X = randi([a b],N,M)将下限默认为1。

请参见以下区别。

Comparison of randi and randn

randi(Imax)

编辑:根据@Max的建议,我添加了N = 500; % Number of samples a = 1; % Lower integer bound b = 60; % Upper integer bound X = randi([a b],N,1); % Random integers between [a,b] Y = randn(N,1); figure, hold on, box on histogram(X) histogram(Y) legend('randi[1,60]','randn','Location','southeast') xlabel('Result') ylabel('Observed Frequency') title({'randi([a b],N,1) vs randn(N,1)';'N = 500'})

Comparison of randi and 60*randn

60*randn
相关问题