Reputation: 39
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!
Upvotes: 1
Views: 55
Reputation: 39
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.
Upvotes: 0
Reputation: 45741
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,:)
Upvotes: 1
Reputation: 114786
For sampling at random, matlab has randsample
:
rowIdx = randsample( size(A,1), k, true );
B = A(rowIdx,:);
Upvotes: 1