Artur Castiel
Artur Castiel

Reputation: 185

2x2 Array Permutation in Matlab with no loop

I'm currently working on a projec where I have an array and I'm suppose to do a 2x2 permutation with all elements without using an array I have something like this:

A = [ 1 , 3 , 5 , 7]

and I wanna get something like this

1 1
1 3
1 5
1 7
3 1
3 3
3 5
3 7
5 1
5 3
5 5
5 7
7 1
7 3
7 5
7 7

I would also be interesting getting a function where I can choose if a number can permuted with itself ( egg: no 77 66 55) or if the order matters (egg:5 3 equals to 3 5, therefore only on entry)

Upvotes: 0

Views: 110

Answers (2)

user2261062
user2261062

Reputation:

If you want to have repeated combinations (where order matters) use perms and take unique rows for the first two columns.

Example:

A = [ 1 , 3 , 5 , 7]
R = perms(A)
unique(R(:,1:2), 'rows')

ans =

 1     3
 1     5
 1     7
 3     1
 3     5
 3     7
 5     1
 5     3
 5     7
 7     1
 7     3
 7     5

If however you want truly unique combinations, use combnk

Example:

A = [ 1 , 3 , 5 , 7]
combnk(A, 2)    % all combinations using 2 elements

ans =

 5     7
 3     7
 3     5
 1     7
 1     5
 1     3

Upvotes: 2

Suever
Suever

Reputation: 65430

You could easily do this with meshgrid

[x,y] = meshgrid(A, A);
out = [x(:), y(:)];

%    1     1
%    1     3
%    1     5
%    1     7
%    3     1
%    3     3
%    3     5
%    3     7
%    5     1
%    5     3
%    5     5
%    5     7
%    7     1
%    7     3
%    7     5
%    7     7

You could remove self-matches (i.e. 5 5, 7 7, etc.)

out(out(:,1) == out(:,2),:) = []

%    1     3
%    1     5
%    1     7
%    3     1
%    3     5
%    3     7
%    5     1
%    5     3
%    5     7
%    7     1
%    7     3
%    7     5

And you could remove duplicates when the order matters by first sorting along the columns and then taking the unique rows

out = unique(sort(out, 2), 'rows')

%    1     3
%    1     5
%    1     7
%    3     5
%    3     7
%    5     7

Upvotes: 3

Related Questions