Dividing a cell array into permutations of two column cell

1 view (last 30 days)
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.
  5 Comments
Cedric
Cedric on 26 Sep 2017
Edited: Cedric on 26 Sep 2017
How could we know that? What is the logic for defining what is equivalent to what? How does that works with four letters? Ok, I am starting to see that the irregularities in your example are not a mistake but there is some aggregation. Yet, what defines equivalences?
folira 81
folira 81 on 26 Sep 2017
@Cedric You are right. I revised the question. Please see the end.

Sign in to comment.

Answers (1)

Cedric
Cedric on 26 Sep 2017
Edited: Cedric 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'
  5 Comments
Cedric
Cedric on 26 Sep 2017
Edited: Cedric on 26 Sep 2017
When you run my example as is (copy from the code box, paste in the command window), do you get an error? If so, which version of MATLAB are you using? If not, please copy an example that generates the error.
Cedric
Cedric on 28 Sep 2017
Did you find what the problem was on your system/content?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!