## How do I create a vector combinations in pairs

on 18 Sep 2013

### Azzi Abdelmalek (view profile)

How do I create a vector combinations in pairs ,with no repeated elements ,for example :

A(1,2,3,4)

1,2

1,3

1,4

2,1

2,3

2,4

3,1

3,2

3,4

4,1

4,2

4,3

I tried to use some commands like : perms And combnk , thanks in advanced

## Products

No products are associated with this question.

### Azzi Abdelmalek (view profile)

on 18 Sep 2013
Edited by Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 18 Sep 2013

```a=fliplr(fullfact([4 4]))
a(~diff(a')',:)=[]
```

or

```[ii,jj]=ndgrid(1:4,1:4);
a=[jj(:) ii(:)];
a(~(a(:,1)-a(:,2)),:)=[]
```

luis

### luis (view profile)

on 19 Sep 2013

thank you, is what I needed I have a question, how do I create a vector combinations for a vector of n elements and choose if I want the combinations of two elements,three or n elements.

Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 19 Sep 2013
```n=4
m=3  % number of combinations
a=fliplr(fullfact(ones(1,m)*n));
b=sort(a,2);
idx=any(~diff(b')',2);
a(idx,:)=[]
```

### Jan Simon (view profile)

on 19 Sep 2013
Edited by Jan Simon

### Jan Simon (view profile)

on 19 Sep 2013

You find many solutions in the FileExchange, e.g.:

### Roger Stafford (view profile)

on 19 Sep 2013

What you are asking for in this comment are known as the partial permutations. I don't know if matlab has such a routine but you can use 'nchoosek' and 'perms' to create one. Let A be a row vector of n elements and let the number of these to be selected in each permutation be called r.

``` c = nchoosek(A,r)';
ncr = size(c,2);
p = perms([1:r]);
pr = size(p,1);
p = reshape(p',1,[]);
B = zeros(ncr*pr,r);
for k = 1:ncr
B((k-1)*pr+1:k*pr,:) = reshape(c(p,k),r,[])';
end```

B will be the desired list of partial permutations.

### Roger Stafford (view profile)

on 19 Sep 2013

Here is a more compact way of using 'nchoosek' and 'perms'.

``` c = nchoosek(A,r)';
B = reshape(c(perms(1:r)',:),r,[])';```

where A, r, and B are as before.

### Andrei Bobrov (view profile)

on 19 Sep 2013
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 19 Sep 2013

```d = fullfact([4 4]);
out = d(diff(d,[],2)~=0,:);
```

and

```A = [8 2 9 6 1];
n = 3;
ix = fullfact(ones(1,n)*numel(A));
out = A(ix(all(diff(sort(ix,2),[],2),2),:));
```

and using the ideas by Roger Stafford (they very nice)

```c = nchoosek(A,r)';
p = perms([1:r]);
s = size(c);
c(reshape(bsxfun(@plus,p',reshape((0:s(2)-1)*s(1),1,1,[])),s(1),[])');
```

### Jos (10584) (view profile)

on 19 Sep 2013

The simplest way is to create all N*N combinations and weed out the N ones that have the same value.

```N = 4 ;
A = 1:N ;
```
```[b2,b1] = ndgrid(A) ; % generalization
q = b1~=b2 ;
% q = ~eye(N) ; % they are all on the diagonal
B = [b1(q) b2(q)]
```

#### Join the 15-year community celebration.

Play games and win prizes!

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