# Dividing a cell array into permutations of two column cell

1 view (last 30 days)
folira 81 on 26 Sep 2017
Commented: Cedric Wannaz on 28 Sep 2017
Assume I have this cell array:
in={'A' 'B' 'C'};
I would like to get possible \t separated permutations of in in two columns as:
out=
'A' 'B C'
'B' 'A C'
'C' 'A B'
'A B' 'C'
'A C' 'B'
'B C' 'A'
For a cell in={'A' 'B' 'C' 'D'} of length 4, there should be 14 different rows in out e.g., 'A B' 'C D'. How to get out for any cell in of length n?
We suppose transposition in single element of a cell is not allowed. That is 'A' 'B C' is read in the same way as 'A' 'C B'. I also need the code can handle words (strings of any type) as the same as 'A' and 'B'. That is 'Alice_' '2John' can be taken in instead of 'A' or 'B' which a tab delimiter should be considered to separate them in output when located in the same cell element.
folira 81 on 26 Sep 2017
@Cedric You are right. I revised the question. Please see the end.

Cedric Wannaz on 26 Sep 2017
Edited: Cedric Wannaz on 26 Sep 2017
EDIT 1:
Here it goes:
words = {'A', 'B', 'C', 'D'} ;
n = length( words ) ;
wordIds = arrayfun( @(k) nchoosek( 1:n,k ), 1:n-1, 'UniformOutput', false ) ;
wordIds = cellfun( @(m) mat2cell( m, ones(size(m, 1), 1), size(m, 2) ), wordIds, 'UniformOutput', false ) ;
wordIds = vertcat( wordIds{:} ) ;
output = arrayfun( @(k){sprintf('%s\t', words{wordIds{k}}), sprintf('%s\t', words{wordIds{end-k+1}})}, ...
(1:numel(wordIds)).', 'UniformOutput', false ) ;
output = strtrim( vertcat( output{:} )) ;
with that you get (where the irregular spacing comes from tabs):
output =
14×2 cell array
'A' 'B C D'
'B' 'A C D'
'C' 'A B D'
'D' 'A B C'
'A B' 'C D'
'A C' 'B D'
'A D' 'B C'
'B C' 'A D'
'B D' 'A C'
'C D' 'A B'
'A B C' 'D'
'A B D' 'C'
'A C D' 'B'
'B C D' 'A'
FORMER: I had misunderstood the question.
>> in = {'A', 'B', 'C'} ;
>> out = in(perms(1:length(in)))
out =
6×3 cell array
'C' 'B' 'A'
'C' 'A' 'B'
'B' 'C' 'A'
'B' 'A' 'C'
'A' 'C' 'B'
'A' 'B' 'C'
Cedric Wannaz on 28 Sep 2017
Did you find what the problem was on your system/content?