Say I want 5 numbers between 1 to 10. However, I do not want any number to be repeated. How do I do this?
I thought of doing
randi([1,length(a)])
One way to do it is by using randperm
:
N = 10; % Numbers from 1 to N will be permuted
n = 5; % Numbers to be extracted
x = randperm(N); % Permute numbers between 1 and N
x = x(1:n); % Retain first n
This can be generalized to any set of values:
N = 10; % Length of vector of N numbers to be permuted
y = randn(N, 1); % Vector from which you want to extract values
n = 5; % Numbers to be extracted
x = randperm(N); % Permute numbers between 1 and N
x = y(x(1:n)); % Retain first n of y
The problem is when N is large and n is small:
tic
N = 1e7;
n = 2;
x = randperm(N);
x = x(1:n);
toc
Then you need to find a better solution. If you have the Statistics Toolbox, try:
tic
x = randsample(N, n, false);
toc
Another approach, which is also slow but doesn't make use of randperm
or randsample
:
N = 1e7;
n = 2;
y = randn(N, 1);
tic
x = randn(N, 1);
[x x] = sort(x);
x = y(x(1:n));
toc