试图为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
问题是randn
生成遵循标准Normal distribution的随机数,例如正常(mu = 0,std = 1)。
正如@Banghua Zhao指出的那样,你想要randi
函数,我将添加它们将在整数边界(称为discrete uniform distribution)之间的整数(包含)中均匀分布。
代码X = randi([a b],N,M)
将生成均匀分布在区间[a,b]上的整数的NxM矩阵。调用randi(Imax)
将下限默认为1。
请参阅下面的差异。
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'})
编辑:在@Max的建议下,我添加了60*randn
。
% MATLAB R2017a
W = 60*randn(N,1);
figure, hold on, box on
hx = histogram(X,'Normalization','pdf')
hw = histogram(W,'Normalization','pdf')
legend('randi[1,60]','60*randn','Location','southeast')
xlabel('Result')
ylabel('Observed Estimated Density')
title({'randi([a b],N,1) vs 60*randn(N,1)';['N = ' num2str(N)]})