필터 지우기
필터 지우기

How can I generate random numbers with constraints?

조회 수: 8 (최근 30일)
Craig
Craig 2013년 4월 25일
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?

답변 (3개)

Tanguy
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

Thorsten
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])

Craig Cowled
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, :);

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by