问题描述:

I was wondering if there was a way to generate all possible permutations for 2 vectors. I know that I can use perms, but that just works for one vector.

What I would like is to input the vector [1 2 3]

and would get out

V1 = [] V2 = [1 2 3]

V1 = [1 2 3] V2 = []

V1 = [1] V2 = [2 3]

V1 = [2] V2 = [1 3]

...

Also could I store all of these permutations in a cell array becuase they all have different lengths so a Matrix won't work.

网友答案:

Is this what you want?

output = {};
v = [1 2 3];  % input
N = length(v);
for k=1:2^N
    m = logical( bitget(k, 1:N) );  % mask selecting elements of v1
    v1 = v(m);
    v2 = v(~m);
    output{end+1} = {v1, v2};
end
网友答案:

In almost one line, the credit should go to seb though.

v = [1 2 3 4]; 
N = numel(v);

out = cellfun(@(x) {v(x) v(~x)}, mat2cell( logical( bsxfun(@bitget,(1:2^N)', (1:N)) ) ,ones(1,2^N),N) , 'uni', 0)

My old answer, clumsy, but works:

A = arrayfun(@(x) nchoosek(V,x), 1:numel(V), 'uni',0);
B = cellfun(@(x) mat2cell(x,ones(1,size(x,1)),size(x,2)),A,'uni',0);

V1 = vertcat({[]},B{:});
V2 = cellfun(@(x) setdiff(V,x), V1, 'uni',0);

gives:

>> celldisp(V1)

V1{1} =
     []
V1{2} =
     1
V1{3} =
     2
V1{4} =
     3
V1{5} =
     1     2
V1{6} =
     1     3
V1{7} =
     2     3
V1{8} =
     1     2     3

and for V2 right the opposite.

网友答案:

Try the following solution:

a=num2cell(1:3);
output1=cellfun(@(x) nchoosek(1:3,x),a,'UniformOutput',false);
output_reverse=cellfun(@(x) nchoosek(3:-1:1,x),a(2:3),'UniformOutput',false);

For a sequence of 1,2,3, the output would be as follows:

output1{1}=

     1
     2
     3

output1{2}=

     1     2
     1     3
     2     3

output1{3}=

     1     2     3

Execute the output_reverse line only when you require the reverse combinations also. Hope this is what you are looking for.

网友答案:

Use a loop over all possible divisions. For each division, compute a mask (logical index) that tells which elements go to V1 and which go to V2. The following assumes order is not important, i.e. [1],[2 3] is the same division as [1], [3 2].

vector = [1 2 3]; %// example data
N = numel(vector); %// number of elements
NN = 2^N; %// number of results
V1 = cell(1,NN); %// intiallize
V2 = cell(1,NN); %// intiallize
for n = 0:NN-1;
    mask = logical(dec2bin(n,N)-'0'); %// logical index for values in V1
    V1{n+1} = vector(mask);
    V2{n+1} = vector(~mask);
end
相关阅读:
Top