Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient generation of permutation matrices in MATLAB

I'm trying to generate a 100-by-5 matrix where every line is a permutation of 1..100 (that is, every line is 5 random numbers from [1..100] without repetitions).

So far I've only been able to do it iteratively with a for-loop. Is there a way to do it more efficiently (using fewer lines of code), without loops?

N = 100;
T = zeros(N, 5);

for i = 1:N
   T(i, :) = randperm(100, 5);
end
like image 280
kotleta2007 Avatar asked Nov 27 '25 23:11

kotleta2007


1 Answers

Let

N = 100; % desired number of rows
K = 5;   % desired number of columns
M = 100; % size of population to sample from

Here's an approach that's probably fast; but memory-expensive, as it generates an intermediate M×N matrix and then discards N-K rows:

[~, result] = sort(rand(N, M), 2);
result = result(:, 1:K);
like image 52
Luis Mendo Avatar answered Dec 02 '25 03:12

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!