Dividing a cell array into permutations of two column cell
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Cedric
am 26 Sep. 2017
Bearbeitet: Cedric
am 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?
Antworten (1)
Cedric
am 26 Sep. 2017
Bearbeitet: Cedric
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!