-2

how would you use randperm to randomly pick three numbers out of a range of 5 in a vector?

i have a vector like this:

A = [1 2 3 4 5 6 7 8 9 10]

now from every 5 consecutive values i want to randomly pick 3 of them:

A_result = [1 3 5 6 7 9]

any help is appreciated!

ocelot
  • 71
  • 1
  • 1
  • 9
  • 1
    Start with, how would you use `randperm` to randomly pick three numbers out of a vector of five? – nkjt Aug 06 '14 at 09:33

3 Answers3

1

You can use reshape and randsample

rA = reshape( A, 5, [] ); % groups of 5 in a a row
A_result = rA( randsample( 5, 3, false ), : );
A_result = reshape( A_result, 1, [] );
Shai
  • 111,146
  • 38
  • 238
  • 371
1

This one uses different random indices in every 5-group.

A = [1 2 3 4 5 6 7 8 9 10]
B = reshape(A,5,[]) % (5 x 2)
ind = cell2mat(arrayfun(@(x)sort(randperm(5,3))',1:size(B,2),'UniformOutput',false)) % (3 x 2), row indices into B
ind = bsxfun(@plus,ind,size(B,1)*(0:size(B,2)-1)) % (3 x 2), linear indices into B
C = B(ind) % (3 x 2) result
C(:)' % result vector

Every sort(randperm(5,3))' call generates a random column vector with 3 ascending numbers from 1 to 5, like [1;3;4] or [2;4;5]. arrayfun with the dummy argument x calls this 2 times in this example, because A consists of 2 sub-vectors of length 5. With the argument 'Uniform output' set to false, it generates a cell array of these random vectors, and cell2mat converts it to the (3 x 2)-matrix ind. The bsxfun call converts the values in the matrix ind to a matrix of linear indices into matrix B or A.

For your (900 x 25)-matrix, do

A = rand(900,25);  % (900 x 25)
B = A';  % (25 x 900)
ind = cell2mat(arrayfun(@(x)sort(randperm(25,17))',1:size(B,2),'UniformOutput',false));  % (17 x 900), row indices into B
ind = bsxfun(@plus,ind,size(B,1)*(0:size(B,2)-1));  % (17 x 900), linear indices into B
C = B(ind);  % (17 x 900), result
Daniel1000
  • 779
  • 4
  • 11
  • can you explain a little? – ocelot Aug 07 '14 at 08:34
  • my A is now not just a vector but a matrix in size (900,25), where in every row are 25 elements from which i want to randomly pick 17 and in the end the result should have a size of (900,17). if i use your code with my matrix instead of B the result is in a completly different size. why so? – ocelot Aug 07 '14 at 11:45
1

You can pre-generate all possible picking patterns, and then randomly select one such pattern for each group. This approach is suitable for small group sizes, otherwise it may use a lot of memory.

A = 1:10; %// example data
n = 5; %// group size. Assumed to divide numel(A)
k = 3; %// how many to pick from each group

S = numel(A);
patterns = nchoosek(1:n, k); %// all possible picking patterns
K = size(patterns, 1);
p = randi(K, S/n, 1); %// generate random indices for patterns
pick = bsxfun(@plus, patterns(p,:).', (0:n:S-1)); %'// to linear indices
A_result = A(pick(:));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147