Translated by このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

Generating matrix of integers with distinct rows

Henry Shackleton

Henry Shackleton (view profile)

さんによって質問されました 2019 年 5 月 18 日

さんによって 編集されました 2019 年 5 月 20 日 11:39

さんの 回答が採用されました
I am trying to generate an NxM matrix consisting of integers between 1 and P. Assume M < P. For each row, I would like the M integers to be distinct. This can easily be accomplished by generating each row with the command randperm(P, M). However, in addition to that, I would like for each of the N rows to be a different set of integers (ideally all rows would be distinct under permutations - i.e, if [1,2,3] was a row, I would like to disallow repetitions of [1,2,3] in addition to arbitrary permutations of those integers. This may be too tricky though, in which case I'm fine just excluding [1,2,3]). Is there any simple way of accomplishing this?
For example, let P = 4, and consider trying to generate a 3x2 matrix. The following would be allowed:
1 2
3 4
1 3
but not
1 2
2 1
4 3

0 件のコメント

サインイン to comment.

R2019a

2 件の回答

2019 年 5 月 18 日

2019 年 5 月 20 日 11:39
採用された回答

In this method, we'll assign a random permutation to each row, row-by-row, and if it's not a different set of integers than the previous rows, it keeps trying again. "mat" is the final matrix.
Note that this could lead to an infinite loop of failed attempts under some initial conditions but the two inf statements toward the top will help to avoid that.
N = 10;
M = 4; %m < p
P = 9;
% make sure user isn't asking for more combinations than what exists!
if N > nchoosek(P,M)
error('Impossible! N cannot be greater than nchoosek(P,M).'
end
% make sure user isn't asking for more samples than exist!
if M > P
error('Impossible! M cannot be greater than P.'
end
mat = [randperm(P,M); zeros(N-1,M)];
while any(mat(:)==0)
% Current row number
r = find(mat(:,1)==0,1);
% assign next row
mat(r,:) = randperm(P,M);
% determine if new row is unique; if not, set back to 0s
if ismember(sort(mat(r,:)),sort(mat(1:r-1,:),2),'rows')
mat(r,:) = 0;
end
end
One way to visually inspect the matrix is to sort by row and then list unique rows.
sort(mat,2)
% or
unique(sort(mat,2),'rows')

0 件のコメント

サインイン to comment.

Walter Roberson (view profile)

2019 年 5 月 18 日

https://en.m.wikipedia.org/wiki/Combinatorial_number_system
Generate N integers in the range up to combs(P, M). Use the combinatorial number system to go directly to particular combinations. That gives you the unordered content of each row which you can then permute.

0 件のコメント

サインイン to comment.