How to choose a random value that was previously excluded from the selection
3 answers
This approach is generalized ... A
can have any values, some numbers, repeating or non-repeating, any number can also be generated (up to, of course numel(A)
).
Code:
A = randi(50,3,3); %// replace this with your own matrix
idx = 1:numel(A); %// generating linear indices
noOfRandNos = 5; %// How many such numbers do you want?
randNos(noOfRandNos,1) = 0; %// pre Allocation
%// This loop is run as many times as the number of such numbers you require.
%// Maximum possible runs will be equal to the numel(A).
for ii = 1:noOfRandNos
randidx = randi(numel(idx)); %// generating a rand Indx within the current size of idx
randNos(ii) = A(idx(randidx)); %// Getting corresponding number in-turn from the indx
idx(randidx) = []; %// removing the particular indx so that it is not repeated
end
Run example:
>> A
A =
12 28 25
23 27 32
49 12 34
>> randNos
randNos =
28
49
34
12
32
+2
source to share
Create a list of random numbers within a range and pick one at a time
minimum=1;
maximum=16;
randomNumbers=randperm(maximum-minimum+1)+minimum-1
and the sample output is randomNumbers=[7 13 2 15 12 4 16 11 9 5 3 1 14 6 8 10]
. You can display each number sequentially using for example
for k=1:maximum+1-minimum
randomNumbers(k)
end
+3
source to share
To select 5
numbers from a set 1:16
without repeating: use randsample
:
result = randsample(1:16, 5);
+1
source to share