Can randperm () generate multiple random permutations?

In matlab

p = randperm (n, k) returns a row vector containing k unique integers randomly selected from 1 to n inclusive.

Is it possible to call randperm () to return several lines of vectors, each of which has a value above? If not, is there another way to generate multiple random permutations?

In this case, avoiding the loop in this case will be faster?

Thank!

+5
source share
3 answers

RANDPERM itself returns only one permutation. If you want to avoid a loop, you can call it with ARRAYFUN:

Nperm = 5; 
N = 6;
result = arrayfun(@(x)randperm(N),(1:Nperm)','UniformOutput',0);

This will return an array of Nperm x 1 cells. To convert it to a matrix, you can use CELL2MAT:

result = cell2mat(result);

PERMS, , .

FileExchange ALLCOMB, PERMS .

+5

, ,

permN = 5; 
permK = 4; 
nPerms = 10;
nGoodPerms = 0;
nMaxFailedTries = 100; 
nFailedTries = 0;

permList = cell(nPerms, 1);

while nGoodPerms < nPerms && nFailedTries <= nMaxFailedTries
    candidatePerm = randperm(permN, permK);
    if any(cellfun(@(x)~isempty(x) && all(x == candidatePerm), permList))
        nFailedTries = nFailedTries + 1;
    else
        nGoodPerms = nGoodPerms + 1;
        permList{nGoodPerms} = candidatePerm;
    end
end

permList = cell2mat(permList{1:nGoodPerms});

, , , ( ). , , nPerms (.. , permN permK).

+1

p = randperm(n):

Matlab 2010a k . randperm code

[~, p] = sort(rand(1,n));

you will see that it is very easy to change it so that it permutes the melements n(now the result has size mx n):

[~, p] = sort(rand(m,n), 2);

Regardingp = randperm(n,k) :

I do not know how Matlab does this in this case, since my version does not support it. You can always do as described above and then crop:

p = p(:,1:k);

Not very effective for kmuch less n.

+1
source

All Articles