I'm trying to wrangle combnk to generate all the combinations of strings in a cell. E.g.:
someStrings = {'a','b','dog','goat'};
results = arrayfun(@(k) combnk(someStrings,k),1:length(someStrings),'UniformOutput',0);
This gives me a 4*1
cell array of cell arrays with the following dimensions:
{4x1 cell} {6x2 cell} {4x3 cell} {1x4 cell}
What I want is a 15*1
cell array of cell arrays, each of size {1xN}
; i.e. 4 cell arrays of size {1,1}
, 6 of size {1,2}
, etc. How can I do this efficiently?
EDIT: Okay, 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 that into one line? How do you index into a cell array like "{:}", but in the line the cell array was created?
You can achieve it as follows:
intermResults=cellfun(@(x) num2cell(x,2),results,'uni',0);
finalResults=vertcat(intermResults{:});
Explaination: If you look at your results
variable, you have those 15 cells. You just need to extract out each row and make it a cell. This is what num2cell(x,2)
does. By wrapping it into cellfun
, I apply it to each cell in the cell array results
. Now you have a 1x4
cell in which each row of results has been converted into a separate cell. You just need to concatenate it to produce the final answer. That's what vertcat(intermResults{:})
does.