Reputation: 25
I need obtain a vector with n
numbers disposed in random order in MatLab. How can I do it?
If I use, for example, randi(10,1,10)
, I will obtain random values, but I have no garantee that all the numbers will be in the sequence.
For example:
I need a vector with all the numbers 1,2,3,4,5,6,7,8,9,10
, disposed in a random order, like in 2,5,3,6,8,10,4,7,9,1
.
Upvotes: 0
Views: 133
Reputation: 114230
It appears that you are looking for the randperm
function. From the docs:
p = randperm(n)
returns a row vector containing a random permutation of the integers from 1 ton
inclusive.
Your example would be randperm(10)
.
There is an optional second argument that you could pass in to determine how many elements will be chosen. For example, randperm(10, 5)
would choose five random numbers from 1 to 10.
You can also use the results of randperm
to shuffle or select from an arbitrary vector. Say you wanted the numbers 101 to 110 in random order instead of 1 to 10:
nums = 101:110;
nums = nums(randperm(numel(nums)));
Upvotes: 1