How can I generate random numbers with constraints?

12 views (last 30 days)
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?

Answers (3)

Tanguy
Tanguy on 25 Apr 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 on 25 Apr 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 on 25 Apr 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, :);

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!