1

Suppose there are a matrix of three row vectors

A = [1,2;
     1,3;
     2,3]

I would like to create a new matrix B which draws two vectors from A with repetitions, and there are 3^2 possible combinations. Some simple implementation is as follows:

For i = 1:3
    c = A(i,:);
    for j=1:3
        d = A(j,:);
        B = [c;d];
    end
end

But, in general, if I need to choose k vectors from n vectors, what is the more general way to write such loop? It's difficult to continue write loop using i, j, ... I guess. Thanks!

Shai
  • 111,146
  • 38
  • 238
  • 371
ximu
  • 39
  • 1
  • 1
  • 8
  • It is better [not to use `i` and `j` as variable names in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Shai Apr 21 '16 at 10:13

3 Answers3

1

You can just use randi for this to pick k uniformly distributed numbers in the range 1:n (with replacement)

k = 2;
n = size(A,1);
rowIdx = randi(n,k)
B = A(rowIdx,:)
Dan
  • 45,079
  • 17
  • 88
  • 157
1

For sampling at random, matlab has randsample:

rowIdx = randsample( size(A,1), k, true );
B = A(rowIdx,:);
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Thanks! but maybe I am wrong, if I use such random sampling, it returns me only one instance? How can I keep track of all possible combinations of the k draws from n vectors? In this case, there are 9 possibilities, how can I find out all 9 cases? – ximu Apr 21 '16 at 13:40
  • 1
    @ximu then you need to use `nchoosek` function – Shai Apr 21 '16 at 14:40
0

Thanks for all previous suggestions. In the end I figure out what I want is called permutations with repetitions. The matlab function permun from file exchange solves my problem.

ximu
  • 39
  • 1
  • 1
  • 8