Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

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

Asked by Molly

Molly

on 16 Jun 2013
Accepted Answer by Andrei Bobrov

Andrei Bobrov

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

0 Comments

Molly

Molly

Products

No products are associated with this question.

1 Answer

Answer by Andrei Bobrov

Andrei Bobrov

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

1 Comment

Molly

Molly

on 16 Jun 2013

Thank you, very elegant.

Andrei Bobrov

Andrei Bobrov

Contact us