Permutation of an array

31 ビュー (過去 30 日間)
Doobie
Doobie 2017 年 5 月 8 日
コメント済み: Walter Roberson 2017 年 5 月 8 日
Is there a built-in matlab function that gives a certain number of permutations of an array? For example:
Take array:
A = [1 2 3 4];
Now there are 24 different permutations. I know that perms(A) would give me all 24 permutations of array A, but I don't need all 24. I only want 4 out of 24. So the function I'm looking for could give me the following matrices:
1 2 3 4 3 2 1 4 1 2 3 4
2 4 3 1 2 1 3 4 3 2 1 4
4 3 1 2 2 3 4 1 3 4 2 1
4 1 2 3 4 1 2 3 4 3 2 1
The important thing is that the selection of the 4 has to be random. So whenever I run my function, I expect to get different 4 (of course, because it is random, I could get the exact same 4 but you get the idea).
Is there a function that does this? If not, could someone direct me towards a code?

回答 (2 件)

Jan
Jan 2017 年 5 月 8 日
Start with:
A = [1 2 3 4];
M = perms(A);
Then pick your submatrix randomly:
P = M(randperm(24, 4), :)

Walter Roberson
Walter Roberson 2017 年 5 月 8 日
編集済み: Walter Roberson 2017 年 5 月 8 日
A( randperm(length(A)) )
which you can repeat 4 times.
  2 件のコメント
Doobie
Doobie 2017 年 5 月 8 日
編集済み: Doobie 2017 年 5 月 8 日
This is not what I'm looking for. Because this is a random process repeated 4 times, it could give the same permutation twice. I want 4 distinct permutations.
Walter Roberson
Walter Roberson 2017 年 5 月 8 日
There is no Mathworks provided function for this purpose.
rows_needed = 4;
cols_needed = length(A);
permidx = [];
more_needed = rows_needed;
while more_needed > 0
[~, trial_idx] = sort( rand(more_needed, cols_needed), 2 );
permidx = unique([permidx; trial_idx], 'rows', 'stable');
more_needed = rows_needed - size(permidx,1);
end
randperms = A(permidx);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by