how can i build a function that can generate 5 random numbers

is there a way to build a function() that once called, it will give in response 5 random numbers between 1 and 40, even if its a matrix?

3 Comments

even if its a matrix
What do you mean?
You can use randi for 5 random numbers:
randi([1 40],1,5)
In a way, i need to create an entire function that will randomly return when called 5 numbers (5, 7, 3, without 1.37 or 39.99) thats between 1 and 40 included. Something like (1:1:40), but everytime i need to receive different numbers between 2 succesive executions of this function. What i mean by "it can be a matrix" is the fact that it can be [1,7,3], or [3;8;20].
Are you wanting to iterate through all of the combinations of 40 items taken 5 at a time? There are 658008 of those. Or do you want all of the permutations of 40 items taken 5 at a time? There are 6799294027065814452880093913300965785600000000 of those.
When you say you want different numbers between consecutive calls, then do all of the numbers have to be different, or do you just not want the same list of numbers twice in a row? For example would [3 9 10 27 31] followed by [1 9 27 30 38] be acceptable ?

Sign in to comment.

 Accepted Answer

As you mentioned in your comment, that the random value should not repeat between consecutive calls to the function. You will need to create a persistent variable so that the function can remember the last vector and generate the new vector based on it. Here is an example,
function out = randVector()
persistent lastValue;
if isempty(lastValue)
lastValue = 0;
end
while 1
randVec = randi([1 40], 1, 5);
if ~any(ismember(randVec, lastValue))
break;
end
end
lastValue = randVec;
out = randVec;
end
Each call to randVector() will generate a vector of 5 random number from 1 to 40. And no repetition happens between consecutive calls.

More Answers (1)

If you just need to do this once then
randperm(40, 5)
If you need to create a number of these then there is a way using sort() but no direct call for it.

1 Comment

Also to expand on that, randperm() gives random integer numbers without repeated numbers being possible. randi() will give random integers but repeats are possible.

Sign in to comment.

Categories

Tags

Community Treasure Hunt

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

Start Hunting!