How can I generate random numbers with constraints?
12 次查看(过去 30 天)
显示 更早的评论
Hello, I'm pretty new to Matlab and could use help.
I'm trying to set up a random number generation that holds my constraints.
I want a 1x7 matrix of random numbers ranging from 3 to 18, I attempted x=unidrnd((3:18),1,7) but that gave me an error.
I know x=unidrnd(18,1,7) works, but it will also choose 1 and 2 which I do not want.
I also attempted with x=randi([3 18], 7), but I ended up with a 7x7 matrix; I only want a 1x7.
Am I going about this the right way?
0 个评论
回答(3 个)
Tanguy
2013-4-25
you're close to the right answer.
With randi, you can choose the size of your matrix. If you just put '7', Matlab will give you a square matrix 7*7.
But if you want a 1*7 matrix, just ask it :
x=randi([3 18], 1, 7)
have a nice day
0 个评论
Thorsten
2013-4-25
randi was introduced in R2008A according to the internet
If you do have a version of Matlab without randi, you can use the following code.
% generate Nsamples integer random numbers between (and including) a and b
a = 3;
b = 18;
Nsamples = 7;
Nsamples = 1000; % choose a large number to test
x = a - 1 + ceil((b - a + 1)*rand([Nsamples 1]));
% RAND never returns 0 or 1
Evaluate result
[v n] = unique(x);
stem(v, n/Nsamples, 'b.-')
box off
xlabel('Random numbers')
title(['Frequency of occurrences (' int2str(Nsamples) ' samples)'])
ylabel('Frequency of occurrence')
set(gca, 'XTick', [a:b])
0 个评论
Craig Cowled
2013-4-25
I think you have actually answered your own question. If x = randi([3 18], 7); gives you a 7 x 7 matrix of random numbers between 3 and 18, then you only need to accept the first row. i.e., x1 = x(1, :);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!