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!