How can I generate random numbers with constraints?

12 visualizaciones (últimos 30 días)
Craig
Craig el 25 de Abr. de 2013
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?

Respuestas (3)

Tanguy
Tanguy el 25 de Abr. de 2013
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 el 25 de Abr. de 2013
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 el 25 de Abr. de 2013
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, :);

Categorías

Más información sobre Random Number Generation en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by