Cell array array of arrays of various sizes into a cell array of cell arrays of size {1xN}
I am trying to unwind a combnk to generate all combinations of rows in a cell. For example:.
someStrings = {'a','b','dog','goat'};
results = arrayfun(@(k) combnk(someStrings,k),1:length(someStrings),'UniformOutput',0);
This gives me a cell array of cell 4*1
arrays with the following dimensions:
{4x1 cell} {6x2 cell} {4x3 cell} {1x4 cell}
What I want is a cell array of cell 15*1
arrays, each with a size {1xN}
; that is, 4 array cells in size {1,1}
, 6 in size {1,2}
, etc. How can I do this efficiently?
EDIT: Ok, now I'm here:
results = transpose(arrayfun(@(k) num2cell(combnk(someStrings,k),2),1:length(someStrings),'UniformOutput',0));
finalResults = vertcat(results{:});
Is it possible to turn this into one line? How do you index a cell array like "{:}", but a cell array was created in the string?
source to share
You can achieve this in the following way:
intermResults=cellfun(@(x) num2cell(x,2),results,'uni',0);
finalResults=vertcat(intermResults{:});
Explanation: If you look at your variable results
, you have these 15 cells. You just need to extract each row and make it a cell. This is what it does num2cell(x,2)
. By packing it in cellfun
, I am applying it to every cell in the cell array results
. You now have a cell 1x4
where each row of results has been converted to a separate cell. You just need to concatenate it to get the final answer. What it does vertcat(intermResults{:})
.
source to share
You can do it like this:
m = dec2bin(1:2^numel(someStrings)-1)-'0'; %// each row contains indices of a combination
[~, s] = sort(sum(m,2)); %// compute sum of each row, sort and get sorting indices
m = m(s,:); %// sort rows according to sum
[jj, ii] = find(m.'); %'// find column indices (jj), ordered by row (ii)
result = accumarray(ii, jj, [], @(x){someStrings(x)}); %// group col indices of each row
This gives for your example someStrings
,
>> result result = {1x1 cell} {1x1 cell} {1x1 cell} {1x1 cell} {1x2 cell} {1x2 cell} {1x2 cell} {1x2 cell} {1x2 cell} {1x2 cell} {1x3 cell} {1x3 cell} {1x3 cell} {1x3 cell} {1x4 cell}
Where
>> result{1}
ans =
'goat'
>> result{2}
ans =
'dog'
>> result{3}
ans =
'b'
>> result{4}
ans =
'a'
>> result{5}
ans =
'dog' 'goat'
>> result{6}
ans =
'b' 'goat'
[...]
>> result{15}
ans =
'a' 'b' 'dog' 'goat'
source to share