Generating matrix of integers with distinct rows
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Henry Shackleton
am 18 Mai 2019
Bearbeitet: Adam Danz
am 20 Mai 2019
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 Kommentare
Akzeptierte Antwort
Adam Danz
am 18 Mai 2019
Bearbeitet: Adam Danz
am 20 Mai 2019
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 Kommentare
Weitere Antworten (1)
Walter Roberson
am 18 Mai 2019
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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!