Dividing a cell array into permutations of two column cell
이전 댓글 표시
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
Cedric
2017년 9월 26일
why 14?
Guillaume
2017년 9월 26일
Yes don't understand where the 14 comes from. For 4 elements you have 24 permutations, multiply that by 3 different columns where you can put your joining tab and you have 42 possibilities.
In your example with 3 elements, you're missing another 6 possibilities:
'A' 'C B'
'B A' 'C'
'B' 'C A'
'C A' 'B'
'C B' 'A'
'C' 'B A'
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
2017년 9월 26일
답변 (1개)
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'
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!