Randomly choose any number of elements within a given sample randomly

666 Views Asked by At

If I want to arbitraraly choose any number $(1\sim9)$ of arbitrarily elements within $(1\sim9)$:

Ex:
1. $n = 3$ (randomly) $\rightarrow$ choose $"1,4,9"$ (randomly & no repeat)
2. $n = 2$ (randomly) $\rightarrow$ choose $"9,10"$ (randomly & no repeat)

How to use Matlab to implement it?

  1. I know randsample; however, randsample can only choose one value randomly.
  2. Use for loop. The bad news is this method will repeat the choice.

Any good way?

2

There are 2 best solutions below

0
On BEST ANSWER
n = randi(9); % number of elements to pick: choose uniformly between 1 and 9
result = randsample(9, n); % pick n elements from 1,...,9 uniformly without replacement
4
On

[a,b]=sort(rand(1,9));b([1 2 3])
EDIT
There are a lot more sets of five-from-nine than one-from-nine. If you want to make all these sets equally likely, (and so choose five of them more often than one of them), you could do

result = find(rand(1,9)>0.5);

This has the disadvantage that, once in 512, you get no numbers :(