How to sequentially add rows to a matrix according to certain contingencies?

10 views (last 30 days)
The matrix below, allPairs, contains all combinations of pairs of 1, 2, and 3. I want first to permute the rows randomly, as I do using permRows and permAllPairs.
allPairs=[1 1; 2 1; 3 1; 1 2; 2 2; 3 2; 1 3; 2 3; 3 3]
allPairs =
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
>> permRows=randperm(size(allPairs,1));
>> permRows
permRows =
6 1 7 4 9 5 8 3 2
permAllPairs = allPairs(permRows(1:9),:)
permAllPairs =
3 2
1 1
1 3
1 2
3 3
2 2
2 3
3 1
2 1
After that, I want to make a new matrix (newPairs) by successively adding each row from permAllPairs into newPairs, according to some rules.
My rules are:
(1) the same row can't be added twice (so if row 3 of permAllPairs, 1,3 was added into newPairs, then 1, 3 can't be added again.)
(2) The flipped row also can't be added. (So if 1, 3 was added, then 3, 1 can't be added to newPairs.)
If this were to work, I would have a 2x6 matrix, something like FakeNew below.
fakeNew =
1 1
3 1
1 2
2 2
2 3
3 3
I feel like the code that does what I want would be similar in spirit to the terribly wrong code below.
newPairs=[];
for i = 1:length(permAllPairs)
if permAllPairs(i,:) ~= newPairs(i,:) & fliplr(newPairs(i,:))
newPairs(i,:) == permAllPairs(i,:)
end
end
newPairs

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 16 Jun 2013
[ii,jj] = ndgrid(1:3);
a = [ii(:),jj(:)];
a1 = a(randperm(length(a)),:);
[b2 b2] = unique(sort(a1,2),'rows');
out = a1(b2,:);

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!